Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

In this page you can find the example usage for org.json JSONObject get.

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:menusearch.json.JSONProcessor.java

/**
    */*  w  w w  . ja v a  2 s .c o m*/
    * @param JSON string: requires the JSON string of the parameters the user enter for the search
    * @return RecipeSummaryList: a RecipeSummaryList where it contains information about the recipes that matches the search the user made
    * @throws java.io.IOException
    */
public static RecipeSummaryList parseRecipeMatches(String results) throws IOException {
    CourseList courseList = new CourseList();
    RecipeSummaryList list = new RecipeSummaryList();
    JSONTokener tokenizer = new JSONTokener(results);
    JSONObject resultList = new JSONObject(tokenizer);
    JSONArray matches = resultList.getJSONArray("matches");
    for (int i = 0; i < matches.length(); i++) {
        RecipeSummary r = new RecipeSummary();
        JSONObject currentRecipe = matches.getJSONObject(i);
        JSONObject imageUrls = currentRecipe.getJSONObject("imageUrlsBySize");
        String link = "90";
        String number = imageUrls.getString(link);
        r.setImageUrlsBySize(number);

        String source = (String) currentRecipe.getString("sourceDisplayName");
        r.setSourceDisplayName(source);

        JSONArray listOfIngredients = currentRecipe.getJSONArray("ingredients");
        for (int n = 0; n < listOfIngredients.length(); n++) {
            String currentIngredients = listOfIngredients.getString(n);
            r.ingredients.add(currentIngredients);
        }

        String id = (String) currentRecipe.getString("id");
        r.setId(id);

        String recipe = (String) currentRecipe.get("recipeName");
        r.setRecipeName(recipe);

        JSONArray smallImage = currentRecipe.getJSONArray("smallImageUrls");
        for (int l = 0; l < smallImage.length(); l++) {
            String currentUrl = (String) smallImage.get(l);
            r.setSmallImageUrls(currentUrl);
        }
        int timeInSeconds = (int) currentRecipe.getInt("totalTimeInSeconds");
        r.setTotalTimeInSeconds(timeInSeconds);

        String a = "attributes";
        String c = "course";
        if (currentRecipe.has(a)) {
            JSONObject currentAttributes = currentRecipe.getJSONObject(a);
            if (currentAttributes.has(c)) {
                for (int j = 0; j < currentAttributes.getJSONArray(c).length(); j++) {
                    String course = currentAttributes.getJSONArray(c).getString(j);
                    courseList.add(course);
                }
                r.setCourses(courseList);
            }
        }

        CuisineList cuisineList = new CuisineList();

        if (currentRecipe.has(a)) {
            JSONObject currentAttributes = currentRecipe.getJSONObject(a);
            if (currentAttributes.has("cuisine")) {
                for (int j = 0; j < currentAttributes.getJSONArray("cuisine").length(); j++) {
                    String currentCuisine = currentAttributes.getJSONArray("cuisine").getString(j);
                    cuisineList.add(currentCuisine);
                }
                r.setCusines(cuisineList);
            }
        }

        String f = "flavors";
        JSONObject currentFlavors;
        if (currentRecipe.has(f) == true) {

            if (currentRecipe.isNull(f) == false) {
                currentFlavors = currentRecipe.getJSONObject(f);
                double saltyRating = currentFlavors.getDouble("salty");
                double sourRating = currentFlavors.getDouble("sour");
                double sweetRating = currentFlavors.getDouble("sweet");
                double bitterRating = currentFlavors.getDouble("bitter");
                double meatyRating = currentFlavors.getDouble("meaty");
                double piguantRating = currentFlavors.getDouble("piquant");
                r.flavors.setSalty(saltyRating);
                r.flavors.setSour(sourRating);
                r.flavors.setSweet(sweetRating);
                r.flavors.setBitter(bitterRating);
                r.flavors.setMeaty(meatyRating);
                r.flavors.setPiquant(piguantRating);
            }
            if (currentRecipe.get(f) == null) {
                r.flavors = null;
            }
            if (currentRecipe.get(f) == null)
                r.flavors = null;
        }

        double rate = currentRecipe.getInt("rating");
        r.setRating(rate);

        list.matches.add(i, r);

    }

    return list;

}

From source file:fr.liglab.adele.cilia.workbench.restmonitoring.utils.http.CiliaRestHelper.java

private static Map<String, String> getComponentPropertiesFromJSON(JSONObject json) throws CiliaException {
    Map<String, String> retval = new HashMap<String, String>();
    try {//from   w  ww . j a va  2  s .c o  m
        JSONObject prop = (JSONObject) json.get("Properties");
        String[] keys = JSONObject.getNames(prop);
        for (String key : keys) {
            String value = prop.get(key).toString();
            retval.put(key, value);
        }
    } catch (JSONException e) {
        String message = "Error while parsing JSON message";
        throw new CiliaException(message, e);
    }

    return retval;
}

From source file:fr.liglab.adele.cilia.workbench.restmonitoring.utils.http.CiliaRestHelper.java

public static String getStateVarValue(PlatformID platformID, String chainName, String compoName,
        String stateVarName) throws CiliaException {
    String target = "/cilia/runtime/" + chainName + "/components/" + compoName + "/rawdata/" + stateVarName;
    String message = HttpHelper.get(platformID, target);
    JSONObject json = string2json(message);

    try {/*from w w  w  . j  a v a2  s. com*/
        Object value = json.get("Measures");
        return value.toString();
    } catch (JSONException e) {
        throw new CiliaException("Can't get measure", e);
    }
}

From source file:io.starter.reactjs.ignite.Generator.java

public static String getJSXFromJSON(JSONObject job) {
    StringBuffer sb = new StringBuffer();

    sb.append("// component jsx");

    sb.append(indent);//w ww  .  j  ava  2s.  c  om
    sb.append("\n");

    String componentName = formatString(job.get("name").toString());
    Iterator<String> names = job.keys();
    while (names.hasNext()) {
        // lookup the component mapping
        String name = names.next();
        String compName = appComponentMap.get(name);
        String componentJSX = componentMapNative.get(compName);
        if (componentJSX != null) {
            sb.append(indent);
            sb.append(indent);
            // look up the component and style for the object
            componentJSX = StringTool.replaceText(componentJSX, "${styles.component}",
                    "{styles." + componentName + "}");

            sb.append(componentJSX);
            sb.append("\n");
        }
    }

    // create the components
    String componentString = sb.toString();

    // replace ${content}
    String componentCode = StringTool.replaceText(componentInitCodeNative, "${content}", componentString);

    sb = new StringBuffer();

    sb.append("// component styles");
    sb.append("\n");
    // create the styles

    sb.append(indent);
    sb.append(componentName + ": {");
    sb.append("\n");
    names = job.keys();
    while (names.hasNext()) {
        String name = names.next();

        String styleName = styleMap.get(name);
        if (styleName != null) {
            sb.append(indent);
            sb.append(indent);
            sb.append(name);
            sb.append(":");
            sb.append(styleName);
            sb.append(",");
            sb.append("\n");
        }
    }
    sb.append(indent);
    sb.append("},"); // end component styles
    sb.append("\n");

    String styleString = sb.toString();

    // replace ${styles}
    String styleCode = StringTool.replaceText(styleInitCodeNative, "${styles}", styleString);

    sb = new StringBuffer(componentCode);
    sb.append("\n");
    sb.append(styleCode);
    sb.append("\n");
    return sb.toString();
}

From source file:edu.asu.msse.sgowdru.moviemediaplayerrpc.MainActivity.java

void loadRPCMovies() {
    JSONArray arr;/*from   ww w.ja v  a 2 s .  c om*/
    List<String> ls = new ArrayList<>();
    try {
        //Call async method to retrieve the movie list names and check in the movie list
        MethodInformation mi = new MethodInformation("http://10.0.2.2:8080/", "getTitles", new String[] {});
        JSONObject ac = new AsyncCollectionConnect().execute(mi).get();
        arr = (JSONArray) ac.get("result");

        for (int i = 0; i < arr.length(); i++) {
            System.out.println("Loading Movie title " + arr.get(i) + " from RPC");
            addMoviesNotInListFromRPC((String) arr.get(i));
        }
    } catch (Exception ex) {
        android.util.Log.w(this.getClass().getSimpleName(), "Exception creating adapter: " + ex.getMessage());
    }
}

From source file:edu.asu.msse.sgowdru.moviemediaplayerrpc.MainActivity.java

void addMoviesNotInListFromRPC(String searchString) {
    JSONObject result;/* w  w w.  j  a  v a  2s.  c  om*/
    try {
        MethodInformation mi = new MethodInformation("http://10.0.2.2:8080/", "get",
                new String[] { searchString });
        JSONObject ac = new AsyncCollectionConnect().execute(mi).get();
        result = (JSONObject) ac.get("result");

        String title = result.getString("Title");
        String genre = result.getString("Genre");
        String year = result.getString("Year");
        String actors = result.getString("Actors");
        String dd = result.getString("Rated");
        String videoFiles = result.getString("Filename");

        System.out.println("Loading Movie details for title " + searchString + " from RPC and adding it to DB");
        //Execute the Sqlite query to insert into local DB
        crsDB.execSQL("Insert into Movies (Title, Years, Rated, Genre, Actors, VideoFile) VALUES('" + title
                + "', '" + year + "', '" + dd + "', '" + genre + "', '" + actors + "', '" + videoFiles + "');");
    } catch (Exception ex) {
        android.util.Log.w(this.getClass().getSimpleName(), "Exception creating adapter: " + ex.getMessage());
    }
}

From source file:org.academia.servlet.SMatricula.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// www  . j  a v a 2s  .  c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            jb.append(line);
        }
        //System.out.println(jb.toString());
        String datt = String.valueOf(jb.toString());

        JSONObject jsonObj = new JSONObject(datt);

        BAlumno oBAlumno = new BAlumno();
        String value = (String) jsonObj.get("nombre");
        oBAlumno.setNombre(value);

        value = (String) jsonObj.get("apellidoPaterno");
        oBAlumno.setApellidoPaterno(value);

        value = (String) jsonObj.get("apellidoMaterno");
        oBAlumno.setApellidoMaterno(value);

        value = (String) jsonObj.get("dni");
        oBAlumno.setDni(value);

        value = (String) jsonObj.get("direccion");
        oBAlumno.setDireccion(value);

        oBAlumno.setEstado(true);
        oBAlumno.setIdSalon(5);
        oBAlumno.setIdExamen(5);

        int idAlumno = new DAOAlumno().registrarAlumno(oBAlumno);

        BMatricula oBMatricula = new BMatricula();

        value = (String) jsonObj.get("escuela");
        oBMatricula.setEscuela(value);
        value = (String) jsonObj.get("idciclo");
        oBMatricula.setIdCiclo(Integer.parseInt(value));

        oBMatricula.setIdAlumno(idAlumno);
        oBMatricula.setIdSecretario(1);
        oBMatricula.setMonto(360.0);

        boolean flag = new DAOMatricula().registrarAlumno(oBMatricula);

        if (idAlumno != 0 && flag == true) {
            String json1 = new Gson().toJson("Alumno matriculado!");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(json1);
        } else {
            String json1 = new Gson().toJson("Error al matricular Alumno");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(json1);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fr.bmartel.android.notti.service.bluetooth.events.BluetoothObject.java

public static BluetoothObject parseArrayList(Intent intent) {

    ArrayList<String> actionsStr = intent.getStringArrayListExtra("");
    if (actionsStr.size() > 0) {
        try {/*from   w  ww .j ava  2  s. c om*/
            JSONObject mainObject = new JSONObject(actionsStr.get(0));
            if (mainObject.has(BluetoothConst.DEVICE_ADDRESS) && mainObject.has(BluetoothConst.DEVICE_NAME)) {

                return new BluetoothObject(mainObject.get(BluetoothConst.DEVICE_ADDRESS).toString(),
                        mainObject.get(BluetoothConst.DEVICE_NAME).toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:config.Manejador.java

public Object Select() throws JSONException {
    JSONObject js_obj = new JSONObject(this.src_archivo);
    return js_obj.get(this.nom_coleccion);
}

From source file:config.Manejador.java

public JSONObject Select(JSONObject parametros) throws JSONException {
    // validar si el string es un object o un array
    JSONObject js_obj = new JSONObject(this.src_archivo);
    JSONArray js_array = (JSONArray) js_obj.get(this.nom_coleccion);

    JSONObject search;//  w ww.j  ava  2 s.c  o  m
    JSONObject retorno = this.dont_exists;

    Iterator it_p = parametros.keys();
    String param = (String) it_p.next();

    boolean encontrado = false;
    for (int i = 0, j = js_array.length(); i < j; i++) {
        search = js_array.getJSONObject(i);
        Iterator<String> it = search.keys();

        while (it.hasNext()) {
            String key = it.next();
            if (key.equals(param)) {
                String busqueda1 = search.get(key).toString();
                String busqueda2 = parametros.get(param).toString();

                if (busqueda1 == null ? busqueda2 == null : busqueda1.equals(busqueda2)) {
                    encontrado = true;
                    search.put("idx", i);
                    retorno = search;
                    break;
                }
            }
        }

        if (encontrado) {
            break;
        }
    }

    return retorno;
}