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.ibm.pickmeup.utils.MessageConductor.java

/**
 * Steer the message according to the rules related to the message payload and topic
 *
 * @param payload as a String// w w w .  j  a v a  2  s.  c o m
 * @param topic   as a String
 * @throws JSONException
 */
public void steerMessage(String payload, String topic) throws JSONException {
    Log.d(TAG, ".steerMessage() entered");

    // create a JSONObject from the payload string
    JSONObject jsonPayload = new JSONObject(payload);

    if (jsonPayload.has(Constants.TYPE) && jsonPayload.has(Constants.DRIVER_ID)
            && jsonPayload.get(Constants.TYPE).equals(Constants.ACCEPT)) {

        // pairing message - get the driverId and send it to the router
        String driverId = jsonPayload.getString(Constants.DRIVER_ID);
        Intent actionIntent = new Intent(Constants.ACTION_INTENT_ROUTE_MESSAGE);
        actionIntent.putExtra(Constants.ROUTE_MESSAGE_TYPE, Constants.ACTION_INTENT_DRIVER_ACCEPTED);
        actionIntent.putExtra(Constants.DRIVER_ID, driverId);
        context.sendBroadcast(actionIntent);
    } else if (topic.contains(Constants.PICTURE) && jsonPayload.has(Constants.URL)) {

        // driver picture message - get the driverPicture as bytes array and send it to the router
        String urlStr = jsonPayload.getString(Constants.URL);
        byte[] decodedPictureAsBytes = Base64.decode(urlStr.substring(urlStr.indexOf(",")), Base64.DEFAULT);
        Intent actionIntent = new Intent(Constants.ACTION_INTENT_ROUTE_MESSAGE);
        actionIntent.putExtra(Constants.ROUTE_MESSAGE_TYPE, Constants.ACTION_INTENT_DRIVER_DETAILS_RECEIVED);
        actionIntent.putExtra(Constants.DRIVER_PICTURE, decodedPictureAsBytes);
        context.sendBroadcast(actionIntent);
    } else if (topic.contains(Constants.DRIVER_HEAD_PREFIX) && jsonPayload.has(Constants.NAME)
            && jsonPayload.has(Constants.CONNECTION_TIME)) {

        // driver name message - get the name and send it to the router
        String driverName = jsonPayload.getString(Constants.NAME);
        Intent actionIntent = new Intent(Constants.ACTION_INTENT_ROUTE_MESSAGE);
        actionIntent.putExtra(Constants.ROUTE_MESSAGE_TYPE, Constants.ACTION_INTENT_DRIVER_DETAILS_RECEIVED);
        actionIntent.putExtra(Constants.NAME, driverName);
        context.sendBroadcast(actionIntent);
    } else if (topic.equals(TopicFactory.getInstance(context).getPassengerChatTopic())
            && jsonPayload.has(Constants.FORMAT) && jsonPayload.has(Constants.DATA)) {

        // chat message - get the format and data and send it to the router
        Intent actionIntent = new Intent(Constants.ACTION_INTENT_ROUTE_MESSAGE);
        actionIntent.putExtra(Constants.ROUTE_MESSAGE_TYPE, Constants.ACTION_INTENT_CHAT_MESSAGE_RECEIVED);
        String format = jsonPayload.getString(Constants.FORMAT);
        String data = jsonPayload.getString(Constants.DATA);
        actionIntent.putExtra(Constants.DATA, data);
        actionIntent.putExtra(Constants.FORMAT, format);
        context.sendBroadcast(actionIntent);
    } else if (topic.equals(TopicFactory.getInstance(context).getDriverLocationTopic())
            && jsonPayload.has(Constants.LATITUDE) && jsonPayload.has(Constants.LONGITUDE)) {

        // driver location message - send it directly to the map
        // check for previousCoordinatesReceivedTime to throttle messages within 100 milliseconds
        if (System.currentTimeMillis() - previousCoordinatesReceivedTime > 100) {
            Intent actionIntent = new Intent(Constants.ACTION_INTENT_COORDINATES_CHANGED);
            float lon = Float.parseFloat(jsonPayload.getString(Constants.LONGITUDE));
            float lat = Float.parseFloat(jsonPayload.getString(Constants.LATITUDE));
            actionIntent.putExtra(Constants.LONGITUDE, lon);
            actionIntent.putExtra(Constants.LATITUDE, lat);
            context.sendBroadcast(actionIntent);
            previousCoordinatesReceivedTime = System.currentTimeMillis();
        }
    } else if (topic.equals(TopicFactory.getInstance(context).getPassengerInboxTopic())
            && jsonPayload.has(Constants.TYPE)) {
        if (jsonPayload.get(Constants.TYPE).equals(Constants.TRIP_START)) {

            // trip started message - send it to the router
            Intent actionIntent = new Intent(Constants.ACTION_INTENT_ROUTE_MESSAGE);
            actionIntent.putExtra(Constants.ROUTE_MESSAGE_TYPE, Constants.ACTION_INTENT_START_TRIP);
            context.sendBroadcast(actionIntent);
        } else if (jsonPayload.get(Constants.TYPE).equals(Constants.TRIP_END) && jsonPayload.has(Constants.TIME)
                && jsonPayload.has(Constants.COST) && jsonPayload.has(Constants.DISTANCE)) {

            // trip ended message - collect time, distance, cost and send to the router
            Intent actionIntent = new Intent(Constants.ACTION_INTENT_ROUTE_MESSAGE);
            actionIntent.putExtra(Constants.ROUTE_MESSAGE_TYPE, Constants.ACTION_INTENT_END_TRIP);
            String time = jsonPayload.getString(Constants.TIME);
            String distance = jsonPayload.getString(Constants.DISTANCE);
            String cost = jsonPayload.getString(Constants.COST);
            actionIntent.putExtra(Constants.TIME, time);
            actionIntent.putExtra(Constants.DISTANCE, distance);
            actionIntent.putExtra(Constants.COST, cost);
            context.sendBroadcast(actionIntent);
        } else if (jsonPayload.get(Constants.TYPE).equals(Constants.TRIP_PROCESSED)) {

            // payment processed message - send it directly to the waiting activity
            Intent actionIntent = new Intent(Constants.ACTION_INTENT_PAYMENT_RECEIVED);
            context.sendBroadcast(actionIntent);
        }
    }
}

From source file:com.facebook.samples.sessionlogin.LoginUsingActivityActivity.java

public void getFrinedsBirthDays() {
    Session session = Session.getActiveSession();
    //Session.NewPermissionsRequest newPermissionsRequest=new Session.NewPermissionsRequest(this,Arrays.asList("friends_birthday"));
    //session.requestNewReadPermissions(newPermissionsRequest);
    String fqlQuery = "select uid, name,birthday, is_app_user from user where uid in (select uid2 from friend where uid1 = me())";
    Bundle params = new Bundle();
    params.putString("q", fqlQuery);

    session = Session.getActiveSession();
    com.facebook.Request request = new com.facebook.Request(session, "/fql", params, HttpMethod.GET,
            new com.facebook.Request.Callback() {

                @Override/*from ww  w.  j  a v a  2s  . c o  m*/
                public void onCompleted(Response response) {
                    try {
                        GraphObject go = response.getGraphObject();
                        JSONObject jso = go.getInnerJSONObject();
                        JSONArray jarray = jso.getJSONArray("data");
                        for (int i = 0; i < jarray.length(); i++) {

                            JSONObject jObject = (JSONObject) jarray.get(i);
                            list.add(jObject.getString("name") + jObject.get("birthday"));
                            Log.v("info", jObject.getString("name") + jObject.get("birthday"));

                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Log.v("birthdays", response.toString());
                    showDialog();

                }
            });
    com.facebook.Request.executeBatchAsync(request);
}

From source file:net.freifunk.android.discover.model.NodesResponse.java

@Override
public void onResponse(JSONObject jsonObject) {
    try {/*  ww w  .  ja  va  2  s  .  com*/
        JSONArray node_list = jsonObject.getJSONArray("nodes");
        for (int i = 0; i < node_list.length(); i++) {
            JSONObject node = node_list.getJSONObject(i);
            List<String> mac_list = new ArrayList<String>(1);
            // MAC
            if (node.has("macs")) {
                String[] macs = ((String) node.get("macs")).split(",");
                mac_list = new ArrayList<String>(macs.length);
                for (String mac : macs) {
                    mac_list.add(mac.trim());
                }
            } else {
                mac_list.add(" ");
            }
            // Name
            String name = ((String) node.get("name")).trim();

            // Firmware
            String firmware = String.valueOf(node.get("firmware")).trim();

            // Flags
            Map<String, String> flags = new HashMap<String, String>();
            JSONObject jflags = node.getJSONObject("flags");
            Iterator flag = jflags.keys();
            while (flag.hasNext()) {
                String key = (String) flag.next();
                String val = String.valueOf(jflags.get(key));
                flags.put(key, val);
            }

            // Geo
            LatLng pos = null;
            //               Log.d(TAG, String.valueOf(node.get("geo")));
            if (!String.valueOf(node.get("geo")).equals("null")) {
                JSONArray geo = node.getJSONArray("geo");
                Double lat = (Double) geo.get(0);
                Double lng = (Double) geo.get(1);
                pos = new LatLng(lat, lng);
            }

            // Id
            String id = ((String) node.get("id")).trim();

            Node n = new Node(mac_list, this.mCallingMap.getMapName(), name, firmware, flags, pos, id);
            Node.nodes.add(n);
            mCallback.onNodeAvailable(n);
        }
    } catch (JSONException e) {
        Log.e(TAG, "Seems something went wrong while loading Nodes for " + this.mCallingMap.getMapName() + ":"
                + e.toString());
    } finally {
        mCallback.onResponseFinished(this.mCallingMap);
    }
}

From source file:org.marinemc.util.mojang.MojangUtils.java

public Status getStatus(final MinecraftService service) {
    String status = null;/*from ww  w . jav  a2s  .  c  om*/
    try {
        final URL url = new URL("http://status.mojang.com/check?service=" + service.getURL());
        final BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));
        final Object object = new JSONParser().parse(input);
        final JSONObject jsonObject = (JSONObject) object;
        status = (String) jsonObject.get(service.getURL());
        input.close();
    } catch (final Exception e) {
        return Status.UNKNOWN;
    }
    return status(status);
}

From source file:test.main1.java

public static void main(String myHelpers[]) throws JSONException, IOException {

    File f = new File(
            "C:\\Users\\Bisan Co\\Documents\\NetBeansProjects\\WebApplication1\\src\\java\\test\\newjson.json");

    String jsonString = readFile(f.getPath());

    jsonOut = new JSONTokener(jsonString);
    JSONObject output = new JSONObject(jsonOut);
    ArrayList<user> users = new ArrayList<user>();

    String test1 = "user";
    for (int i = 1; i < 5; i++) {
        user test = new user();
        String id = (String) output.getJSONObject(test1 + i).get("-ID");
        test.setID(id);//from  ww w.j  ava2 s.  c om
        String name = (String) output.getJSONObject(test1 + i).get("Name");
        test.setName(name);
        String dop = (String) output.getJSONObject(test1 + i).get("DOB");
        test.setDOP(dop);
        String email = (String) output.getJSONObject(test1 + i).get("Email");
        test.setEmail(email);
        String title = (String) output.getJSONObject(test1 + i).get("Title");
        test.setTitle(title);
        String phone = (String) output.getJSONObject(test1 + i).get("Phone-no.");
        test.setPhoneNo(phone);
        JSONArray Friends = (JSONArray) output.getJSONObject(test1 + i).getJSONArray("Friends");
        friend test2 = new friend();
        location test3 = new location();
        for (int j = 0; j < Friends.length(); j++) {
            String id1 = Friends.getJSONObject(j).getString("-ID");
            test2.setID(id1);
            String name1 = Friends.getJSONObject(j).getString("name");
            test2.setName(name1);
            String loca = Friends.getJSONObject(j).getString("location");
            test3.setGPS(loca);
            String add = Friends.getJSONObject(j).getString("address");
            test3.setADD(add);
            test2.setLocation(test3);
            test.AddFriend(test2);
        }
        users.add(test);
    }
}

From source file:io.teak.sdk.Helpers.java

private static Map<String, Object> toMap(JSONObject object) throws JSONException {
    Map<String, Object> map = new HashMap<>();

    Iterator keysItr = object.keys();
    while (keysItr.hasNext()) {
        String key = keysItr.next().toString();
        Object value = object.get(key);

        if (value instanceof JSONArray) {
            value = toList((JSONArray) value);
        } else if (value instanceof JSONObject) {
            value = toMap((JSONObject) value);
        }/*from ww  w .j ava  2  s  .c  om*/
        map.put(key, value);
    }
    return map;
}

From source file:org.wso2.carbon.connector.integration.test.shopify.ShopifyConnectorIntegrationTest.java

/**
 * Positive test case for createFulfillment method with mandatory parameters.
 *///from   w w w  . j  a  v  a 2s. c o m
@Test(priority = 1, groups = { "wso2.esb" }, dependsOnMethods = {
        "listOrdersNegativeCase" }, description = "Shopify {createFulfillment} integration test with mandatory parameters.")
public void createFulfillmentWithMandatoryParameters() throws Exception {

    esbRequestHeadersMap.put("Action", "urn:createFulfillment");

    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_createFulfillment_mandatory.json");

    JSONObject esbJsonObject = esbRestResponse.getBody().getJSONObject("fulfillment");

    String apiEndPoint = connectorProperties.getProperty("apiUrl") + "/admin/orders/"
            + connectorProperties.getProperty("orderId") + "/fulfillments/" + esbJsonObject.getString("id")
            + ".json";

    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);

    JSONObject apiJsonObject = apiRestResponse.getBody().getJSONObject("fulfillment");

    Assert.assertEquals(esbJsonObject.get("id"), apiJsonObject.get("id"));
    Assert.assertEquals(esbJsonObject.get("order_id"), apiJsonObject.get("order_id"));
    Assert.assertEquals(esbJsonObject.get("tracking_number"), apiJsonObject.get("tracking_number"));

}

From source file:org.wso2.carbon.connector.integration.test.shopify.ShopifyConnectorIntegrationTest.java

/**
 * Positive test case for createFulfillment method with optional parameters.
 *///from  w  w  w . j  av  a2 s  .c  o m
@Test(priority = 1, groups = { "wso2.esb" }, dependsOnMethods = {
        "createFulfillmentWithMandatoryParameters" }, description = "Shopify {createFulfillment} integration test with optional parameters.")
public void createFulfillmentWithOptionalParameters() throws Exception {

    esbRequestHeadersMap.put("Action", "urn:createFulfillment");

    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_createFulfillment_optional.json");

    JSONObject esbJsonObject = esbRestResponse.getBody().getJSONObject("fulfillment");

    String apiEndPoint = connectorProperties.getProperty("apiUrl") + "/admin/orders/"
            + connectorProperties.getProperty("orderId1") + "/fulfillments/" + esbJsonObject.get("id")
            + ".json";

    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);

    JSONObject apiJsonObject = apiRestResponse.getBody().getJSONObject("fulfillment");

    Assert.assertEquals(esbJsonObject.get("id"), apiJsonObject.get("id"));
    Assert.assertEquals(esbJsonObject.get("order_id"), apiJsonObject.get("order_id"));
    Assert.assertEquals(esbJsonObject.get("tracking_number"), apiJsonObject.get("tracking_number"));
    Assert.assertEquals(esbJsonObject.getJSONArray("line_items").getJSONObject(0).getString("id"),
            apiJsonObject.getJSONArray("line_items").getJSONObject(0).getString("id"));

}

From source file:com.vishnuvalleru.travelweatheralertsystem.MainActivity.java

private Vector<String> getWeatherInfo(LatLng point) {
    Vector<String> vct = new Vector<String>();
    try {//w ww . ja  v a2  s  .  c  om
        JSONObject jsonResponse = JSONReader
                .readJsonFromUrl("http://api.openweathermap.org/data/2.5/weather?lat="
                        + String.valueOf(point.latitude) + "&lon=" + String.valueOf(point.longitude));
        JSONArray tempArr = (JSONArray) jsonResponse.get("weather");
        JSONObject tempJson = (JSONObject) jsonResponse.get("main");
        String wTemp = tempJson.getString("temp");
        int dTemp = (int) ((Double.valueOf(wTemp) - 273) * 1.8 + 32);
        vct.add(String.valueOf(dTemp));
        vct.add(tempJson.getString("humidity"));
        JSONObject jsonWeather = (JSONObject) tempArr.get(0);

        vct.add(jsonWeather.get("description").toString());
        vct.add(jsonResponse.get("name").toString());
        //adding elements to the end

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return vct;
}