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:com.jennifer.ui.chart.widget.LegendWidget.java

@Override
public Object draw() {

    double x = 0, y = 0, total_width = 0, total_height = 0, max_width = 0, max_height = 0;

    for (int i = 0, len = brush.length(); i < len; i++) {
        int index = brush.getInt(i);
        JSONObject brushObject = chart.brush(index);

        JSONArray arr = getLegendIcon(brushObject);

        for (int k = 0, kLen = arr.length(); k < kLen; k++) {
            JSONObject obj = arr.getJSONObject(k);

            double w = obj.getDouble("width");
            double h = obj.getDouble("height");
            Transform icon = (Transform) obj.get("icon");

            //root.append(icon);
            icon.translate(x, y);//from   ww  w  . java  2s  .c  om

            if ("bottom".equals(position) || "top".equals(position)) {
                x += w;
                total_width += w;

                if (max_height < h) {
                    max_height = h;
                }
            } else {
                y += h;
                total_height += h;

                if (max_width < w) {
                    max_width = w;
                }
            }

        }
    }

    if ("bottom".equals(position) || "top".equals(position)) {
        y = ("bottom".equals(position)) ? chart.area("y2") + chart.padding("bottom") - max_height
                : chart.area("y") - chart.padding("top");

        if ("start".equals(align)) {
            x = chart.area("x");
        } else if ("center".equals(align)) {
            x = chart.area("x") + (chart.area("width") / 2.0 - total_width / 2.0);
        } else if ("end".equals(align)) {
            x = chart.area("x2") - total_width;
        }

    } else {
        x = ("left".equals(position)) ? chart.area("x") - max_width : chart.area("x2") + 20;

        if ("start".equals(align)) {
            y = chart.area("y");
        } else if ("center".equals(align)) {
            y = chart.area("y") + (chart.area("height") / 2.0 - total_height / 2.0);
        } else if ("end".equals(align)) {
            y = chart.area("y2") - total_height;
        }

    }

    root.translate(x + 0.5, y + 0.5);

    return new JSONObject().put("root", root);
}

From source file:pt.webdetails.cpf.persistence.PersistenceEngine.java

public ODocument createDocument(String baseClass, JSONObject json) {
    ODocument doc = new ODocument(baseClass);
    @SuppressWarnings("unchecked")
    Iterator<String> fields = json.keys();
    while (fields.hasNext()) {
        String field = fields.next();
        if (field.equals("key")) {
            continue;
        }//  w  w  w.ja  v  a 2s . co m

        try {
            Object value = json.get(field);
            if (value instanceof JSONObject) {

                doc.field(field, createDocument(baseClass + "_" + field, (JSONObject) value));

                JSONObject obj = json.getJSONObject(field);
                logger.debug("obj:" + obj.toString(JSON_INDENT));
            } else {
                doc.field(field, value);
            }

        } catch (JSONException e) {
            logger.error(e);
        }
    }

    return doc;
}

From source file:edu.jhu.cvrg.waveform.utility.WebServiceUtility.java

public static Map<String, String> annotationJSONLookup(String restURL, String... key) {

    Map<String, String> ret = null;
    URL url;//www  . ja  v  a2  s  . com
    HttpURLConnection conn = null;
    try {
        if (System.currentTimeMillis() > waitUntil) {
            url = new URL(restURL);

            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            BufferedReader in = new BufferedReader(new InputStreamReader((conn.getInputStream())));

            String jsonSrc = in.readLine();
            in.close();

            JSONObject jsonObject = new JSONObject(jsonSrc);
            ret = new HashMap<String, String>();

            for (int i = 0; i < key.length; i++) {
                Object atr = jsonObject.get(key[i]);
                String value = "";
                if (atr instanceof JSONArray) {
                    JSONArray array = ((JSONArray) atr);
                    for (int j = 0; j < array.length(); j++) {
                        value += array.getString(j);
                    }
                } else {
                    value = atr.toString();
                }
                if (value.isEmpty()) {
                    value = "No " + key[i] + " found";
                }
                ret.put(key[i], value);
            }
        } else {
            log.warn("Waiting the bioportal server");
        }

    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        //wait for 1 minute
        waitUntil = System.currentTimeMillis() + (1000 * 60);

        log.error(ioe.getMessage());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return ret;
}

From source file:com.rapid.actions.Logic.java

public Logic(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // call the super parameterless constructor which sets the xml version
    super();//from  w  w w .j  ava  2  s . co  m
    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties, except for the ones we want directly accessible
        if (!"conditions".equals(key) && !"conditionsType".equals(key) && !"trueActions".equals(key)
                && !"falseActions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }

    // initialise list
    _conditions = new ArrayList<Condition>();
    // grab conditions from json
    JSONArray jsonConditions = jsonAction.optJSONArray("conditions");

    // if we got some
    if (jsonConditions != null) {
        // loop them
        for (int i = 0; i < jsonConditions.length(); i++) {
            // add to our list
            _conditions.add(new Condition(jsonConditions.getJSONObject(i)));
        }
    }

    // get conditions type
    _conditionsType = jsonAction.getString("conditionsType");

    // grab any successActions
    JSONArray jsonTrueActions = jsonAction.optJSONArray("trueActions");
    // if we had some
    if (jsonTrueActions != null) {
        _trueActions = Control.getActions(rapidServlet, jsonTrueActions);
    }

    // grab any errorActions
    JSONArray jsonFalseActions = jsonAction.optJSONArray("falseActions");
    // if we had some
    if (jsonFalseActions != null) {
        // instantiate our contols collection
        _falseActions = Control.getActions(rapidServlet, jsonFalseActions);
    }

}

From source file:GUI.FormUsuarios.java

/**
 * Creates new form FormUsuarios// w  ww.j av  a  2s  . c o  m
 */
public FormUsuarios() {
    initComponents();

    HttpResponse response;
    response = JSON.request(Config.URL + "usuarios/listartipos.json");
    JSONObject jObject = JSON.JSON(response);
    try {
        System.out.println(jObject.get("code"));
        JSONArray jsonArr = jObject.getJSONArray("data");

        for (int i = 0; i < jsonArr.length(); i++) {
            JSONObject data = jsonArr.getJSONObject(i);
            cb_tipo.addItem(new listaTipo(data.get("idTipo").toString(), data.get("descripcion").toString()));
            ValoresCombobox.put(data.get("descripcion").toString(),
                    Integer.parseInt(data.get("idTipo").toString()));
        }

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

    initializeComponent();
}

From source file:GUI.FormUsuarios.java

private void btn_guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_guardarActionPerformed

    List<NameValuePair> parametros = new ArrayList<NameValuePair>();
    parametros.add(new BasicNameValuePair("nombre", txt_nombre.getText()));
    parametros.add(new BasicNameValuePair("email", txt_email.getText()));
    parametros.add(new BasicNameValuePair("edad", txt_edad.getText()));

    Object item = cb_tipo.getSelectedItem();
    String value = ((listaTipo) item).getKey();

    parametros.add(new BasicNameValuePair("tipo", value));

    String url = "";
    String mensaje_correcto = "";
    String mensaje_error = "";

    if (getID() != null) {

        parametros.add(new BasicNameValuePair("idUsuario", getID()));

        mensaje_correcto = "Usuario Actualizado";
        mensaje_error = "Error actualizar Usuario";
        url = Config.URL + "usuarios/editar.json";
    } else {//from   w  w  w  .  jav  a  2s.co  m
        mensaje_correcto = "Usuario Agregado";
        mensaje_error = "Error agregar Usuario";
        url = Config.URL + "usuarios/agregar.json";
    }

    HttpResponse response = JSON.request(url, parametros);

    JSONObject jObject = JSON.JSON(response);
    int code = Integer.parseInt(jObject.get("code").toString());

    if (code == 201) {
        JOptionPane.showMessageDialog(null, mensaje_correcto);
        this.dispose();
    } else {
        JOptionPane.showMessageDialog(null, mensaje_error);
    }
}

From source file:com.flym.echo24.activity.EditFeedActivity.java

/**
 * This is where the bulk of our work is done. This function is called in a background thread and should generate a new set of data to be
 * published by the loader.//from   w  w  w .  jav a2 s  .co  m
 */
@Override
public ArrayList<HashMap<String, String>> loadInBackground() {
    try {
        HttpURLConnection conn = NetworkUtils
                .setupConnection("https://ajax.googleapis.com/ajax/services/feed/find?v=1.0&q=" + mSearchText);
        try {
            String jsonStr = new String(NetworkUtils.getBytes(conn.getInputStream()));

            // Parse results
            final ArrayList<HashMap<String, String>> results = new ArrayList<>();
            JSONObject response = new JSONObject(jsonStr).getJSONObject("responseData");
            JSONArray entries = response.getJSONArray("entries");
            for (int i = 0; i < entries.length(); i++) {
                try {
                    JSONObject entry = (JSONObject) entries.get(i);
                    String url = entry.get(EditFeedActivity.FEED_SEARCH_URL).toString();
                    if (!url.isEmpty()) {
                        HashMap<String, String> map = new HashMap<>();
                        map.put(EditFeedActivity.FEED_SEARCH_TITLE, Html
                                .fromHtml(entry.get(EditFeedActivity.FEED_SEARCH_TITLE).toString()).toString());
                        map.put(EditFeedActivity.FEED_SEARCH_URL, url);
                        map.put(EditFeedActivity.FEED_SEARCH_DESC, Html
                                .fromHtml(entry.get(EditFeedActivity.FEED_SEARCH_DESC).toString()).toString());

                        results.add(map);
                    }
                } catch (Exception ignored) {
                }
            }

            return results;
        } finally {
            conn.disconnect();
        }
    } catch (Exception e) {
        return null;
    }
}

From source file:screenieup.ImgurUpload.java

/**
 * Parse response to get the required property of the image.
 * @param toParse the property to look for (eg. link / deletehash etc...)
 * @param response the response to be parsed
 * @return string containing the wanted property
 *//*from  ww w . ja v  a 2s .c o  m*/
private String parse(String toParse, String response) {
    JSONObject jsn = new JSONObject(response);
    JSONObject data = (JSONObject) jsn.get("data");
    return (String) data.getString(toParse);
}

From source file:com.microsoft.live.unittest.PostTest.java

@Override
protected void checkValidResponseBody(LiveOperation operation) throws JSONException {
    JSONObject result = operation.getResult();
    String id = result.getString(JsonKeys.ID);
    Object description = result.get(JsonKeys.DESCRIPTION);
    String name = result.getString(JsonKeys.NAME);
    String permissions = result.getString(JsonKeys.PERMISSIONS);
    boolean isDefault = result.getBoolean(JsonKeys.IS_DEFAULT);

    JSONObject from = result.getJSONObject(JsonKeys.FROM);
    String fromId = from.getString(JsonKeys.ID);
    String fromName = from.getString(JsonKeys.NAME);

    Object subscriptionLocation = result.get(JsonKeys.SUBSCRIPTION_LOCATION);
    String createdTime = result.getString(JsonKeys.CREATED_TIME);
    String updatedTime = result.getString(JsonKeys.UPDATED_TIME);

    assertEquals("calendar_id", id);
    assertEquals(JSONObject.NULL, description);
    assertEquals("name", name);
    assertEquals("owner", permissions);
    assertEquals(false, isDefault);/* w  w w. java 2  s  . c o  m*/
    assertEquals("from_id", fromId);
    assertEquals("from_name", fromName);
    assertEquals(JSONObject.NULL, subscriptionLocation);
    assertEquals("2011-12-10T02:48:33+0000", createdTime);
    assertEquals("2011-12-10T02:48:33+0000", updatedTime);
}

From source file:es.deustotech.piramide.utils.net.JSONParser.java

public static Vector<Point> parseFromUrl(HttpEntity httpEntity) {
    if (httpEntity != null) {
        InputStream inStream;/*w  w  w  . j  a v a2s. c  om*/
        try {
            inStream = httpEntity.getContent();
            result = convertStreamToString(inStream);
            points = new Vector<Point>();
            final JSONObject jsonObj = new JSONObject(result);

            final JSONObject result = jsonObj.getJSONObject(Constants.JSON_RESPONSE_DATA);

            //show 8 results
            for (int i = 0; i < 8; i++) {
                final JSONObject resultAux = (JSONObject) result.getJSONArray(Constants.JSON_RESULTS).get(i);
                //               final JSONObject phoneAux    = (JSONObject) resultAux.getJSONArray(Constants.JSON_PHONE_NUMBERS).get(0);

                final Point point = new Point(resultAux.getString(Constants.JSON_TITLE),
                        resultAux.getString(Constants.JSON_STREET), resultAux.getString(Constants.JSON_LAT),
                        resultAux.getString(Constants.JSON_LNG)

                /*new PhoneNumbers(phoneAux.getString(Constants.JSON_TYPE), 
                phoneAux.getString(Constants.JSON_NUMBER)), 
                resultAux.getString(Constants.JSON_CITY), 
                resultAux.getString(Constants.JSON_TITLE), 
                resultAux.getString(Constants.JSON_REGION), 
                resultAux.getString(Constants.JSON_TITLE_NO_FORMATTING), 
                resultAux.getString(Constants.JSON_STREET), 
                resultAux.getJSONArray(Constants.JSON_ADDRESS_LINES).getString(0), 
                resultAux.getString(Constants.JSON_COUNTRY), 
                resultAux.getString(Constants.JSON_LAT), 
                resultAux.getString(Constants.JSON_LNG),
                resultAux.getString(Constants.JSON_TO_HERE), 
                resultAux.getString(Constants.JSON_FROM_HERE)*/);

                points.add(point);
            }

            //            final JSONObject phoneAux    = (JSONObject) result.getJSONArray(Constants.JSON_PHONE_NUMBERS).get(0);

            /*
            Log.i(Constants.TAG, "<jsonobject>\n" + jsonObj.toString() + "\n</jsonobject>");
                    
            final JSONArray nameArray    = jsonObj.names();
            final JSONArray valArray    = jsonObj.toJSONArray(nameArray);
                    
            for(int i=0; i<valArray.length(); i++) {
               Log.e(Constants.TAG, "<jsonname" + i + ">\n" + nameArray.getString(i) + "\n</jsonname" + i + ">\n" 
             + "<jsonvalue" + i + ">\n" + valArray.getString(i) + "\n</jsonvalue" + i + ">");
            }
            jsonObj.put(Constants.SAMPLE_KEY, Constants.SAMPLE_VALUE);
                    
            Log.i(Constants.TAG, "<jsonobject>\n" + jsonObj.toString() + "\n</jsonobject>");
             */

            inStream.close();
        } catch (IllegalStateException ise) {
            Log.d(Constants.TAG, ise.getMessage());
        } catch (IOException ioe) {
            Log.d(Constants.TAG, ioe.getMessage());
        } catch (JSONException je) {
            Log.d(Constants.TAG, je.getMessage());
        }
    } // If the response does not enclose an entity, there is no need
      // to worry about connection release
    return points;
}