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.abc.driver.MainActivity.java

/**
 * ??? /*from  w  ww .ja v a  2 s .co m*/
 * {"result_code":"0","horders":[{"id":6,"shipper_username":
 * "\u674e\u674e\u90bb\u5c45\u5929",
 * "shipper_phone":"","shipper_date":"2015-03-15 00:00:00"
 * ,"shipper_address_code":"110000-110100-110101",
 * "consignee_username":"","consignee_phone"
 * :"","consignee_address_code":"110000-110100-110101",
 * "delivery_time":"0000-00-00 00:00:00"
 * ,"truck_type":"","truck_length":"","cargo_type":"CT1",
 * "cargo_volume":"\u6d4b\u8bd5",
 * "cargo_weight":"\u6d4b\u8bd5\u554a","horder_desc"
 * :"","user_id":9,"status":0, "created_at":"2015-03-15 03:30:50",
 * "updated_at":"2015-03-15 03:30:50"},}]}
 * 
 * @param jsonResult
 */
public void parseJson(JSONObject jsonResult) {
    HashMap<String, Object> mHorder;
    try {
        if (jsonResult.get("horders") != JSONObject.NULL) {
            JSONArray results = jsonResult.getJSONArray("horders");
            if (results.length() < CellSiteConstants.PAGE_COUNT) {
                mHorderTypes[mCurrRadioIdx].hasShowAllHorders = true;
            }

            for (int i = 0; i < results.length(); i++) {
                try {
                    JSONObject resultObj = (JSONObject) results.get(i);
                    mHorder = new HashMap<String, Object>();
                    mHorder.put(CellSiteConstants.SHIPPER_USERNAME,
                            resultObj.getString(CellSiteConstants.SHIPPER_USERNAME));
                    mHorder.put("horder_id", (resultObj).getString(CellSiteConstants.ID));
                    // TODO : 
                    int counter = 0;

                    mHorderTypes[mCurrRadioIdx].nHorders.add(mHorder);
                } catch (Exception e) {
                    mHasExceptionHorder = true;
                    continue;
                }

            }

        }

    } catch (JSONException e) {
        Log.d(TAG, "JSONException" + e.toString());

    }

}

From source file:com.abc.driver.MainActivity.java

/**
 * ??? /*from   w w w.  j a v a  2  s .  c o  m*/
 * {"result_code":"0","horders":[{"id":6,"shipper_username":
 * "\u674e\u674e\u90bb\u5c45\u5929",
 * "shipper_phone":"","shipper_date":"2015-03-15 00:00:00"
 * ,"shipper_address_code":"110000-110100-110101",
 * "consignee_username":"","consignee_phone"
 * :"","consignee_address_code":"110000-110100-110101",
 * "delivery_time":"0000-00-00 00:00:00"
 * ,"truck_type":"","truck_length":"","cargo_type":"CT1",
 * "cargo_volume":"\u6d4b\u8bd5",
 * "cargo_weight":"\u6d4b\u8bd5\u554a","horder_desc"
 * :"","user_id":9,"status":0, "created_at":"2015-03-15 03:30:50",
 * "updated_at":"2015-03-15 03:30:50"},}]}
 * 
 * @param jsonResult
 */
public void parseFHorderJson(JSONObject jsonResult) {
    HashMap<String, Object> mHorder;
    try {
        if (jsonResult.get("horders") != JSONObject.NULL) {
            JSONArray results = jsonResult.getJSONArray("horders");
            if (results.length() < CellSiteConstants.PAGE_COUNT) {
                mFHorderTypes.hasShowAllHorders = true;
            }

            for (int i = 0; i < results.length(); i++) {
                try {
                    JSONObject resultObj = (JSONObject) results.get(i);
                    JSONArray repliedDriversObj = null;
                    mHorder = new HashMap<String, Object>();

                    mHorder.put(CellSiteConstants.ALREADY_REPLIED, 0);
                    try {
                        // 1. ???repliedtag 1 ?0
                        // 2.
                        repliedDriversObj = resultObj.getJSONArray(CellSiteConstants.REPLIED_DRIVERS);
                        if (repliedDriversObj != null) {
                            for (int j = 0; j < repliedDriversObj.length(); j++) {
                                String driver_id = ((JSONObject) repliedDriversObj.get(i))
                                        .getString(CellSiteConstants.DRIVER_ID);
                                if (driver_id.equals("" + app.getUser().getId())) {
                                    mHorder.put(CellSiteConstants.ALREADY_REPLIED, 1);
                                    break;
                                }

                            }
                            mHorder.put(CellSiteConstants.REPLIED_DRIVERS_COUNT, repliedDriversObj.length());
                        }
                    } catch (Exception e) {

                    }

                    mHorder.put(CellSiteConstants.SHIPPER_USERNAME,
                            resultObj.getString(CellSiteConstants.SHIPPER_USERNAME));
                    mHorder.put(CellSiteConstants.HORDER_ID, (resultObj).getString(CellSiteConstants.ID));
                    mHorder.put(CellSiteConstants.SHIPPER_PHONE,
                            (resultObj).getString(CellSiteConstants.SHIPPER_PHONE));
                    mHorder.put(CellSiteConstants.USER_ID, (resultObj).getString(CellSiteConstants.USER_ID));

                    CityDBReader dbReader = new CityDBReader(this.getApplicationContext());
                    mHorder.put(CellSiteConstants.SHIPPER_ADDRESS_NAME, dbReader
                            .getNameFromCode((resultObj).getString(CellSiteConstants.SHIPPER_ADDRESS_CODE_IN)));
                    mHorder.put(CellSiteConstants.CONSIGNEE_ADDRESS_NAME, dbReader
                            .getNameFromCode((resultObj).getString(CellSiteConstants.CONSIGNEE_ADDRESS_CODE2)));
                    mHorder.put(CellSiteConstants.CARGO_TYPE,
                            (resultObj).getString(CellSiteConstants.CARGO_TYPE));
                    mHorder.put(CellSiteConstants.CARGO_WEIGHT,
                            (resultObj).getString(CellSiteConstants.CARGO_WEIGHT));
                    mHorder.put(CellSiteConstants.CARGO_VOLUME,
                            (resultObj).getString(CellSiteConstants.CARGO_VOLUME));
                    mHorder.put(CellSiteConstants.TRUCK_TYPE,
                            (resultObj).getString(CellSiteConstants.TRUCK_TYPE));
                    mHorder.put(CellSiteConstants.HORDER_STATUS,
                            (resultObj).getString(CellSiteConstants.STATUS));
                    mHorder.put(CellSiteConstants.SHIPPER_DATE,
                            (resultObj).getString(CellSiteConstants.SHIPPER_DATE));
                    mHorder.put(CellSiteConstants.HORDER_DESCRIPTION,
                            (resultObj).getString(CellSiteConstants.HORDER_DESCRIPTION));
                    mHorder.put(CellSiteConstants.SHIPPER_USERNAME,
                            (resultObj).getString(CellSiteConstants.SHIPPER_USERNAME));

                    // TODO :
                    int counter = 0;

                    mFHorderTypes.nHorders.add(mHorder);
                } catch (Exception e) {
                    mHasExceptionFHorder = true;
                    continue;
                }

            }

        }

    } catch (JSONException e) {
        Log.d(TAG, "JSONException" + e.toString());

    }

}

From source file:com.abc.driver.MainActivity.java

int replyHorder(String _horderId, String _driverId) {

    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair(CellSiteConstants.HORDER_ID, _horderId));
    postParameters.add(new BasicNameValuePair(CellSiteConstants.DRIVER_ID, _driverId));

    JSONObject response = null;
    try {// ww w.  j  ava2  s  .  c o m
        response = CellSiteHttpClient.executeHttpPost(CellSiteConstants.REQUEST_HODER_URL, postParameters);

        int resultCode = Integer.parseInt(response.get(CellSiteConstants.RESULT_CODE).toString());
        Log.d(TAG, "ResultCode = " + resultCode);
        if (CellSiteConstants.RESULT_SUC == resultCode) {

            // app.startToSearchLoc();
        } else if (resultCode == CellSiteConstants.REGISTER_USER_EXISTS) {
            // ???

        }
        return resultCode;
    } catch (Exception e) {
        Log.d(TAG, "Register by mail fails." + e.getMessage());
        return CellSiteConstants.UNKNOWN_ERROR;
    }
}

From source file:onacodechallenge.ONACodeChallengeTest.java

/**
 * Test of main method, of class ONACodeChallenge.
 *///from  ww w.  ja v  a 2s.  c  o  m
@Test
public void testCalculate() {
    try {
        String fileURl = new File("data/testdata.json").toURI().toURL().toString();

        JSONObject calculate = (JSONObject) app.calculate(fileURl);

        JSONObject numWater = (JSONObject) calculate.get("number_water_points");
        JSONObject ranking = (JSONObject) calculate.get("community_ranking");

        assertEquals(12, calculate.get("number_functional"));
        assertEquals(8, numWater.get("Sangana"));
        assertEquals(50.0f, ranking.get("Machakos"));
    } catch (IOException ex) {
        Logger.getLogger(ONACodeChallengeTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(ONACodeChallengeTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:sh.calaba.driver.server.CalabashProxy.java

/**
 * Redirects the given calabash <code>command</code> to the calabash server of the corresponding
 * session. The command handling of taking screenshots is different from the other calabash
 * command because another URI is used./*ww  w .  j a v  a 2s  . c  om*/
 * 
 * @param command The command to redirect and execute.
 * @param sessionId The test session id.
 * @return The response of the calabash server running on the device.
 */
public JSONObject redirectMessageToCalabashServer(JSONObject command, String sessionId) {
    if (logger.isDebugEnabled()) {
        logger.debug("received command: " + command.toString());
        logger.debug("received sessionId: " + sessionId);
    }
    if (sessionConnectors.containsKey(sessionId)) {
        JSONObject result = null;
        try {
            if ("take_screenshot_embed".equals(command.get("command"))) {
                result = sessionConnectors.get(sessionId).takeScreenshot();
            } else {
                result = sessionConnectors.get(sessionId).execute(command);
            }
        } catch (JSONException e) {
            logger.error("Exception occured: ", e);
            throw new CalabashConnecterException("Json exception occured while executing calabash commands: ",
                    e);
        } catch (IOException e) {
            logger.error("Exception occured: ", e);
            throw new CalabashConnecterException(
                    "IOException exception occured while executing calabash commands: ", e);
        }

        return result;
    } else {
        throw new CalabashConnecterException("Calabash Connector for Session not found: " + sessionId);
    }
}

From source file:com.abc.driver.PersonalActivity.java

public void parseJson(JSONObject jsonResult) {
    JSONObject profileJson = null;
    try {/*w w w  .j  a  va 2 s. c  o m*/
        try {
            profileJson = jsonResult.getJSONObject(CellSiteConstants.PROFILE);
        } catch (Exception e) {
            profileJson = null;
        }
        JSONObject userJson = jsonResult.getJSONObject(CellSiteConstants.USER);
        if (profileJson != null) {
            if (profileJson.get(CellSiteConstants.PROFILE_IMAGE_URL) != JSONObject.NULL) {
                Log.d(TAG, "get the image url");
                app.getUser().setProfileImageUrl(profileJson.getString(CellSiteConstants.PROFILE_IMAGE_URL));

            }
            if (profileJson.get(CellSiteConstants.DRIVER_LICENSE_URL) != JSONObject.NULL) {
                app.getUser()
                        .setDriverLicenseImageUrl(profileJson.getString(CellSiteConstants.DRIVER_LICENSE_URL));
            }
            if (profileJson.get(CellSiteConstants.IDENTITY_CARD_IMAGE_URL) != JSONObject.NULL) {
                app.getUser()
                        .setIdentityImageUrl(profileJson.getString(CellSiteConstants.IDENTITY_CARD_IMAGE_URL));
            }

            if (profileJson.get(CellSiteConstants.NAME) != JSONObject.NULL) {
                app.getUser().setName(profileJson.getString(CellSiteConstants.NAME));
            }

        }
        if (userJson.get(CellSiteConstants.MOBILE) != JSONObject.NULL) {
            app.getUser().setMobileNum(userJson.getString(CellSiteConstants.MOBILE));
        }

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

}

From source file:edu.umass.cs.gigapaxos.paxospackets.AcceptPacket.java

public AcceptPacket(net.minidev.json.JSONObject json) throws JSONException {
    super(json);/*from   www .  j  ava  2s. c om*/
    assert (json.containsKey(RequestPacket.Keys.STRINGIFIED.toString()));
    assert (PaxosPacket.getPaxosPacketType(json) == PaxosPacketType.ACCEPT);
    this.packetType = PaxosPacketType.ACCEPT;
    this.sender = (Integer) json.get(PaxosPacket.NodeIDKeys.SNDR.toString());
    // TODO: why do we need to set paxosID here?
    this.paxosID = (String) json.get(PaxosPacket.Keys.ID.toString());
}

From source file:com.atinternet.tracker.Tool.java

/**
 * Convert a JSONObject to Map/*from   w  ww.  j av a  2 s  .  com*/
 *
 * @param jsonObject JSONObject
 * @return Map
 */
static Map toMap(JSONObject jsonObject) {
    Map<String, Object> map = new HashMap<String, Object>();

    Iterator<String> keysItr = jsonObject.keys();
    while (keysItr.hasNext()) {
        String key = keysItr.next();
        Object value = null;
        try {
            value = jsonObject.get(key);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        map.put(key, value);
    }
    return map;
}

From source file:com.jennifer.ui.chart.grid.DateGrid.java

private void initDomain() {

    if (has("target") && !has("domain")) {

        if (options.get("target") instanceof String) {
            JSONArray list = new JSONArray();
            list.put(options.getString("target"));
            options.put("target", list);
        }/*from  w  w w  .j a  v a2  s. co m*/

        JSONArray target = (JSONArray) options.getJSONArray("target");
        JSONArray domain = new JSONArray();
        JSONArray data = chart.data();

        long min = 0;
        long max = 0;

        boolean hasMin = options.has("min");
        boolean hasMax = options.has("max");

        for (int i = 0, len = target.length(); i < len; i++) {
            String key = target.getString(i);

            for (int index = 0, dataLength = data.length(); index < dataLength; index++) {
                JSONObject row = data.getJSONObject(index);

                long value = 0;

                if (row.get(key) instanceof Date) {
                    value = ((Date) row.get(key)).getTime();
                } else {
                    value = row.getLong(key);
                }

                if (!hasMin) {
                    min = value;
                    hasMin = true;
                } else if (min > value)
                    min = value;

                if (!hasMax) {
                    max = value;
                    hasMax = true;
                } else if (max < value)
                    max = value;
            }

        }

        options.put("max", max);
        options.put("min", min);

        domain.put(min).put(max);

        if (options.optBoolean("reverse", false)) {
            JSONUtil.reverse(domain);
        }

        options.put("domain", domain);

    }

}

From source file:com.util.httpAccount.java

public Account getAccountObject(String tel) {
    String telefono = tel.replace("-", "");
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    //String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json";
    String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/" + telefono + ".json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;/*from  w  ww .j  av  a  2  s. c  o  m*/
    Account account = new Account();
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            if (urlConn != null && urlConn.getInputStream() != null) {
                in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

                BufferedReader bufferedReader = new BufferedReader(in);
                if (bufferedReader != null) {
                    int cp;
                    while ((cp = bufferedReader.read()) != -1) {
                        sb.append((char) cp);
                    }
                    bufferedReader.close();
                }
            }

            String jsonResult = sb.toString();
            // System.out.println(sb.toString());
            //System.out.println("\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
            JSONObject objJason = new JSONObject(jsonResult);
            JSONArray dataJson = new JSONArray();
            dataJson = objJason.getJSONArray("data");

            //System.out.println("objeto normal 1 "+dataJson.toString());
            //
            //
            // System.out.println("\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n");
            String jsonString2 = dataJson.toString();
            String temp = dataJson.toString();
            temp = jsonString2.replace("[", "");
            jsonString2 = temp.replace("]", "");
            // System.out.println("new json string"+jsonString2);

            JSONObject objJson2 = new JSONObject(jsonString2);
            // System.out.println("el objeto simple json es " + objJson2.toString());

            // System.out.println("\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n");
            String account1 = objJson2.optString("account");
            // System.out.println(account1);
            JSONObject objJson3 = new JSONObject(account1);
            //   System.out.println("el ULTIMO OBJETO SIMPLE ES  " + objJson3.toString());
            //   System.out.println("\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n");
            String firstName = objJson3.getString("first_name");
            System.out.println(firstName);
            System.out.println(objJson3.get("language_id"));
            //  System.out.println("\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n");
            Gson gson = new Gson();
            account = gson.fromJson(objJson3.toString(), Account.class);
            //System.out.println(account.getFirst_name());
            // System.out.println(account.getCreation());
            account.setLanguaje_id(objJson3.get("language_id").toString());
            account.setId(objJson3.get("id").toString());
            account.setBalance(objJson3.get("balance").toString());
            System.out.println("el id del account es " + account.getId());

        } else {
            System.out.print("no se pudo conectar con el servidor");
            account = null;
        }

        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }

    return account;
}