Example usage for org.json JSONObject getJSONObject

List of usage examples for org.json JSONObject getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(String key) throws JSONException 

Source Link

Document

Get the JSONObject value associated with a key.

Usage

From source file:org.cohorte.remote.dispatcher.beans.PelixEndpointDescription.java

/**
 * Parses the given JSON object to construct the bean
 * /*w  w w.  ja va  2 s.  c  o m*/
 * @param aJsonObject
 *            A JSON representation of the end point
 * @throws JSONException
 *             Error parsing the JSON object
 */
public PelixEndpointDescription(final JSONObject aJsonObject) throws JSONException {

    // Basic values
    pSender = aJsonObject.getString("sender");
    pUID = aJsonObject.getString("uid");
    pName = aJsonObject.getString("name");

    // Properties
    pProperties = ParseUtils.jsonToMap(aJsonObject.getJSONObject("properties"));

    // Configurations
    pConfigurations = extractStrings(aJsonObject.getJSONArray("configurations"));

    // Specifications
    pSpecifications = extractStrings(aJsonObject.getJSONArray("specifications"));
}

From source file:weathernotificationservice.wns.activities.MainActivity.java

private ParseResult parseTodayJson(String result) {
    try {/* www  .  j  a va 2  s .co  m*/
        JSONObject reader = new JSONObject(result);

        final String code = reader.optString("cod");
        if ("404".equals(code)) {
            return ParseResult.CITY_NOT_FOUND;
        }

        String city = reader.getString("name");
        String country = "";
        JSONObject countryObj = reader.optJSONObject("sys");
        if (countryObj != null) {
            country = countryObj.getString("country");
            todayWeather.setSunrise(countryObj.getString("sunrise"));
            todayWeather.setSunset(countryObj.getString("sunset"));
        }
        todayWeather.setCity(city);
        todayWeather.setCountry(country);

        JSONObject coordinates = reader.getJSONObject("coord");
        if (coordinates != null) {
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
            sp.edit().putFloat("latitude", (float) coordinates.getDouble("lon"))
                    .putFloat("longitude", (float) coordinates.getDouble("lat")).commit();
        }

        JSONObject main = reader.getJSONObject("main");

        todayWeather.setTemperature(main.getString("temp"));
        todayWeather.setDescription(reader.getJSONArray("weather").getJSONObject(0).getString("description"));
        JSONObject windObj = reader.getJSONObject("wind");
        todayWeather.setWind(windObj.getString("speed"));
        if (windObj.has("deg")) {
            todayWeather.setWindDirectionDegree(windObj.getDouble("deg"));
        } else {
            Log.e("parseTodayJson", "No wind direction available");
            todayWeather.setWindDirectionDegree(null);
        }
        todayWeather.setPressure(main.getString("pressure"));
        todayWeather.setHumidity(main.getString("humidity"));

        JSONObject rainObj = reader.optJSONObject("rain");
        String rain;
        if (rainObj != null) {
            rain = getRainString(rainObj);
        } else {
            JSONObject snowObj = reader.optJSONObject("snow");
            if (snowObj != null) {
                rain = getRainString(snowObj);
            } else {
                rain = "0";
            }
        }
        todayWeather.setRain(rain);

        final String idString = reader.getJSONArray("weather").getJSONObject(0).getString("id");
        todayWeather.setId(idString);
        todayWeather.setIcon(
                setWeatherIcon(Integer.parseInt(idString), Calendar.getInstance().get(Calendar.HOUR_OF_DAY)));

        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this)
                .edit();
        editor.putString("lastToday", result);
        editor.commit();

    } catch (JSONException e) {
        Log.e("JSONException Data", result);
        e.printStackTrace();
        return ParseResult.JSON_EXCEPTION;
    }

    return ParseResult.OK;
}

From source file:weathernotificationservice.wns.activities.MainActivity.java

public ParseResult parseLongTermJson(String result) {
    int i;//  ww  w. j a  va2 s.  com
    try {
        JSONObject reader = new JSONObject(result);

        final String code = reader.optString("cod");
        if ("404".equals(code)) {
            if (longTermWeather == null) {
                longTermWeather = new ArrayList<>();
                longTermTodayWeather = new ArrayList<>();
                longTermTomorrowWeather = new ArrayList<>();
            }
            return ParseResult.CITY_NOT_FOUND;
        }

        longTermWeather = new ArrayList<>();
        longTermTodayWeather = new ArrayList<>();
        longTermTomorrowWeather = new ArrayList<>();

        JSONArray list = reader.getJSONArray("list");
        for (i = 0; i < list.length(); i++) {
            Weather weather = new Weather();

            JSONObject listItem = list.getJSONObject(i);
            JSONObject main = listItem.getJSONObject("main");

            weather.setDate(listItem.getString("dt"));
            weather.setTemperature(main.getString("temp"));
            weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description"));
            JSONObject windObj = listItem.optJSONObject("wind");
            if (windObj != null) {
                weather.setWind(windObj.getString("speed"));
                weather.setWindDirectionDegree(windObj.getDouble("deg"));
            }
            weather.setPressure(main.getString("pressure"));
            weather.setHumidity(main.getString("humidity"));

            JSONObject rainObj = listItem.optJSONObject("rain");
            String rain = "";
            if (rainObj != null) {
                rain = getRainString(rainObj);
            } else {
                JSONObject snowObj = listItem.optJSONObject("snow");
                if (snowObj != null) {
                    rain = getRainString(snowObj);
                } else {
                    rain = "0";
                }
            }
            weather.setRain(rain);

            final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id");
            weather.setId(idString);

            final String dateMsString = listItem.getString("dt") + "000";
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(Long.parseLong(dateMsString));
            weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY)));

            Calendar today = Calendar.getInstance();
            if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
                longTermTodayWeather.add(weather);
            } else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) {
                longTermTomorrowWeather.add(weather);
            } else {
                longTermWeather.add(weather);
            }
        }
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this)
                .edit();
        editor.putString("lastLongterm", result);
        editor.commit();
    } catch (JSONException e) {
        Log.e("JSONException Data", result);
        e.printStackTrace();
        return ParseResult.JSON_EXCEPTION;
    }

    return ParseResult.OK;
}

From source file:io.sponges.dubtrack4j.internal.subscription.callback.ChatMessageCall.java

@Override
public void run(JSONObject json) throws IOException {
    String message = json.getString("message");
    String username = json.getJSONObject("user").getString("username");
    String userId = json.getJSONObject("user").getString("_id");
    String roomId = json.getJSONObject("queue_object").getString("roomid");
    long time = json.getJSONObject("queue_object").getLong("updated");

    RoomImpl room = dubtrack.loadRoom(roomId);
    User user = room.getOrLoadUser(userId);

    Message msg = new Message(user, room, time, message);
    dubtrack.getEventBus().post(new UserChatEvent(msg));
}

From source file:io.cslinmiso.line.utils.Utility.java

public static Map getMap(JSONObject object, String key) throws JSONException {
    return toMap(object.getJSONObject(key));
}

From source file:net.majorkernelpanic.spydroid.api.RequestHandler.java

/** 
 * The implementation of all the possible requests is here
 * -> "sounds": returns a list of available sounds on the phone
 * -> "screen": returns the screen state (whether the app. is on the foreground or not)
 * -> "play": plays a sound on the phone
 * -> "set": update Spydroid's configuration
 * -> "get": returns Spydroid's configuration (framerate, bitrate...)
 * -> "state": returns a JSON containing information about the state of the application
 * -> "battery": returns an approximation of the battery level on the phone
 * -> "buzz": makes the phone buuz /*from   w  ww.  j av a2s . c om*/
 * -> "volume": sets or gets the volume 
 * @throws JSONException
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 **/
static private void exec(JSONObject object, StringBuilder response)
        throws JSONException, IllegalArgumentException, IllegalAccessException {

    SpydroidApplication application = SpydroidApplication.getInstance();
    Context context = application.getApplicationContext();

    String action = object.getString("action");

    // Returns a list of available sounds on the phone
    if (action.equals("sounds")) {
        Field[] raws = R.raw.class.getFields();
        response.append("[");
        for (int i = 0; i < raws.length - 1; i++) {
            response.append("\"" + raws[i].getName() + "\",");
        }
        response.append("\"" + raws[raws.length - 1].getName() + "\"]");
    }

    // Returns the screen state (whether the app. is on the foreground or not)
    else if (action.equals("screen")) {
        response.append(application.applicationForeground ? "\"1\"" : "\"0\"");
    }

    // Plays a sound on the phone
    else if (action.equals("play")) {
        Field[] raws = R.raw.class.getFields();
        for (int i = 0; i < raws.length; i++) {
            if (raws[i].getName().equals(object.getString("name"))) {
                mSoundPool.load(application, raws[i].getInt(null), 0);
            }
        }
        response.append("[]");
    }

    // Returns Spydroid's configuration (framerate, bitrate...)
    else if (action.equals("get")) {
        final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

        response.append("{\"streamAudio\":" + settings.getBoolean("stream_audio", false) + ",");
        response.append("\"audioEncoder\":\""
                + (application.audioEncoder == SessionBuilder.AUDIO_AMRNB ? "AMR-NB" : "AAC") + "\",");
        response.append("\"streamVideo\":" + settings.getBoolean("stream_video", true) + ",");
        response.append("\"videoEncoder\":\""
                + (application.videoEncoder == SessionBuilder.VIDEO_H263 ? "H.263" : "H.264") + "\",");
        response.append("\"videoResolution\":\"" + application.videoQuality.resX + "x"
                + application.videoQuality.resY + "\",");
        response.append("\"videoFramerate\":\"" + application.videoQuality.framerate + " fps\",");
        response.append("\"videoBitrate\":\"" + application.videoQuality.bitrate / 1000 + " kbps\"}");

    }

    // Update Spydroid's configuration
    else if (action.equals("set")) {
        final JSONObject settings = object.getJSONObject("settings");
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        final Editor editor = prefs.edit();

        editor.putBoolean("stream_video", settings.getBoolean("stream_video"));
        application.videoQuality = VideoQuality.parseQuality(settings.getString("video_quality"));
        editor.putInt("video_resX", application.videoQuality.resX);
        editor.putInt("video_resY", application.videoQuality.resY);
        editor.putString("video_framerate", String.valueOf(application.videoQuality.framerate));
        editor.putString("video_bitrate", String.valueOf(application.videoQuality.bitrate / 1000));
        editor.putString("video_encoder", settings.getString("video_encoder").equals("H.263") ? "2" : "1");
        editor.putBoolean("stream_audio", settings.getBoolean("stream_audio"));
        editor.putString("audio_encoder", settings.getString("audio_encoder").equals("AMR-NB") ? "3" : "5");
        editor.commit();
        response.append("[]");

    }

    // Returns a JSON containing information about the state of the application
    else if (action.equals("state")) {

        Exception exception = application.lastCaughtException;

        response.append("{");

        if (exception != null) {

            // Used to display the message on the user interface
            String lastError = exception.getMessage();

            // Useful to display additional information to the user depending on the error
            StackTraceElement[] stack = exception.getStackTrace();
            StringBuilder builder = new StringBuilder(
                    exception.getClass().getName() + " : " + lastError + "||");
            for (int i = 0; i < stack.length; i++)
                builder.append("at " + stack[i].getClassName() + "." + stack[i].getMethodName() + " ("
                        + stack[i].getFileName() + ":" + stack[i].getLineNumber() + ")||");

            response.append("\"lastError\":\"" + (lastError != null ? lastError : "unknown error") + "\",");
            response.append("\"lastStackTrace\":\"" + builder.toString() + "\",");

        }

        response.append("\"activityPaused\":\"" + (application.applicationForeground ? "1" : "0") + "\"");
        response.append("}");

    }

    else if (action.equals("clear")) {
        application.lastCaughtException = null;
        response.append("[]");
    }

    // Returns an approximation of the battery level
    else if (action.equals("battery")) {
        response.append("\"" + application.batteryLevel + "\"");
    }

    // Makes the phone vibrates for 300ms
    else if (action.equals("buzz")) {
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(300);
        response.append("[]");
    }

    // Sets or gets the system's volume
    else if (action.equals("volume")) {
        AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (object.has("set")) {
            audio.setStreamVolume(AudioManager.STREAM_MUSIC, object.getInt("set"),
                    AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
            response.append("[]");
        } else {
            int max = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            int current = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
            response.append("{\"max\":" + max + ",\"current\":" + current + "}");
        }
    }

}

From source file:io.selendroid.server.SelendroidSatusHandlerTest.java

public void assertThatGetStatusHandlerIsRegistered() throws Exception {
    HttpResponse response = HttpClientUtil.executeRequest(URL, HttpMethod.GET);
    SelendroidAssert.assertResponseIsOk(response);
    JSONObject result = HttpClientUtil.parseJsonResponse(response);
    SelendroidAssert.assertResponseIsOk(response);

    Assert.assertFalse(result.has("sessionId"));
    JSONObject value = result.getJSONObject("value");
    Assert.assertEquals("dev", value.getJSONObject("build").getString("version"));
}

From source file:com.facebook.android.FieldsConnectionsDialog.java

public FieldsConnectionsDialog(GraphExplorer explorerActivity, JSONObject metadata) {
    super(explorerActivity);
    this.explorerActivity = explorerActivity;

    /*/*from  w  w  w. j av a2 s. c  o m*/
     * Sort the fields and connections
     */
    try {
        sortFields(metadata.getJSONArray("fields"));
        sortConnections(metadata.getJSONObject("connections").names());
    } catch (JSONException e) {
        Toast.makeText(explorerActivity.getBaseContext(), "Fields/Connections could not be fetched.",
                Toast.LENGTH_SHORT).show();
    }

    setTitle(explorerActivity.getString(R.string.fields_and_connections));
    fieldsVector = new Vector<String>();
}

From source file:com.klinker.android.twitter.utils.api_helper.TweetMarkerHelper.java

public boolean getLastStatus(String collection, final Context context) {

    long currentId = sharedPrefs.getLong("current_position_" + currentAccount, 0l);

    boolean updated = false;

    try {/* w w w . ja v  a  2 s . co  m*/
        long startTime = Calendar.getInstance().getTimeInMillis();
        HttpGet get = new HttpGet(postURL + "&" + collection);
        get.addHeader("X-Auth-Service-Provider", SERVICE_PROVIDER);
        get.addHeader("X-Verify-Credentials-Authorization", getAuthrityHeader(twitter));

        HttpClient client = new DefaultHttpClient();

        HttpResponse response = client.execute(get);
        Log.v("talon_tweetmarker",
                "getting id response code: " + response.getStatusLine().getStatusCode() + " for " + screenname);

        long endTime = Calendar.getInstance().getTimeInMillis();

        StatusLine statusLine = response.getStatusLine();

        final long responseTime = endTime - startTime;

        if (endTime - startTime > 15000 && statusLine.getStatusCode() == 200) {
            ((Activity) context).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (sharedPrefs.getBoolean("show_tweetmarker_length", true)) {
                            new AlertDialog.Builder(context).setTitle("Slow TweetMarker Fetch").setMessage(
                                    "TweetMarker successfully fetched it's position, but seemed to take quite a bit of time. "
                                            + "They may be experiencing issues at the moment, you may want to try again in a little while! \n\n"
                                            + "Server Response Time: " + (responseTime / 1000) + " seconds")
                                    .setPositiveButton("Turn Off TM", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            sharedPrefs.edit().putString("tweetmarker_options", "0").commit();
                                            AppSettings.invalidate();
                                        }
                                    }).setNeutralButton(R.string.dont_show_again,
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    sharedPrefs.edit()
                                                            .putBoolean("show_tweetmarker_length", false)
                                                            .commit();
                                                    dialog.dismiss();
                                                }
                                            })
                                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    }).create().show();
                        }
                    } catch (Exception e) {

                    }
                }
            });
        }

        if (statusLine.getStatusCode() == 500 || statusLine.getStatusCode() == 503) {
            // common tweetmarker failure codes
            final StatusLine s = statusLine;

            ((Activity) context).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        new AlertDialog.Builder(context).setTitle("TweetMarker Failure").setMessage("Error: "
                                + s.getStatusCode() + "(" + s.getReasonPhrase() + ")" + "\n\n"
                                + "TweetMarker has been experiencing some issues on their end lately with some apps. They seem intermittent, random, and are causing incredibly slow load times."
                                + "I have been in contact with them, but I would recommend turning off this feature until these issues are resolved.")
                                .setPositiveButton("Turn Off TM", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        sharedPrefs.edit().putString("tweetmarker_options", "0").commit();
                                        AppSettings.invalidate();
                                    }
                                }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }).create().show();
                    } catch (Exception e) {

                    }
                }
            });

            updated = false;
        } else if (statusLine.getStatusCode() == 200) { // request ok
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = rd.readLine()) != null) {
                builder.append(line);
            }

            JSONObject jsonObject = new JSONObject(builder.toString());
            JSONObject timeline = jsonObject.getJSONObject(collection);

            if (timeline != null) {
                currentId = Long.parseLong(timeline.getString("id"));
                int version = Integer.parseInt(timeline.getString("version"));

                Log.v("talon_tweetmarker", "getting tweetmarker," + " version: " + version + " id: " + currentId
                        + " screename: " + screenname);

                int lastVer = sharedPrefs.getInt("last_version_account_" + currentAccount, 0);

                if (lastVer != version) {
                    updated = true;
                }

                sharedPrefs.edit().putInt("last_version_account_" + currentAccount, version).commit();
            }
        } else { // there was an error, we will retry once
            // wait first
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {

            }

            response = client.execute(get);

            statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() == 200) { // request ok
                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));

                String line;
                StringBuilder builder = new StringBuilder();
                while ((line = rd.readLine()) != null) {
                    builder.append(line);
                }

                JSONObject jsonObject = new JSONObject(builder.toString());
                JSONObject timeline = jsonObject.getJSONObject(collection);

                if (timeline != null) {

                    currentId = Long.parseLong(timeline.getString("id"));
                    int version = Integer.parseInt(timeline.getString("version"));

                    Log.v("talon_tweetmarker", "getting tweetmarker," + " version: " + version + " id: "
                            + currentId + " screename: " + screenname);

                    int lastVer = sharedPrefs.getInt("last_version_account_" + currentAccount, 0);

                    if (lastVer != version) {
                        updated = true;
                    }

                    sharedPrefs.edit().putInt("last_version_account_" + currentAccount, version).commit();
                }
            }
        }
    } catch (HttpHostConnectException e) {
        // timeout when connecting to host.
        ((Activity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    new AlertDialog.Builder(context).setTitle("TweetMarker Failure")
                            .setMessage("Timeout connecting to TweetMarker." + "\n\n"
                                    + "TweetMarker has been experiencing some issues on their end lately with some apps. They seem intermittent, random, and are causing incredibly slow load times."
                                    + "I have been in contact with them, but I would recommend turning off this feature until these issues are resolved.")
                            .setPositiveButton("Turn Off TM", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    sharedPrefs.edit().putString("tweetmarker_options", "0").commit();
                                    AppSettings.invalidate();
                                }
                            }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();
                } catch (Exception e) {

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

    }

    Log.v("talon_launcher_stuff", "writing " + currentId + " to shared prefs");
    sharedPrefs.edit().putLong("current_position_" + currentAccount, currentId).commit();
    if (contentProvider) {
        HomeContentProvider.updateCurrent(currentAccount, context, currentId);
    } else {
        try {
            HomeDataSource.getInstance(context).markPosition(currentAccount, currentId);
        } catch (Exception e) {

        }
    }

    return updated;
}

From source file:com.whizzosoftware.hobson.dto.data.DataStreamDTOTest.java

@Test
public void testToJSON() {
    ExpansionFields ef = new ExpansionFields(JSONAttributes.DATA);
    DataStreamDTO dto = createDTO(new ManagerDTOBuildContext.Builder().idProvider(new ContextPathIdProvider())
            .expansionFields(ef).build(), true);
    JSONObject json = dto.toJSON();/*  ww w .  java 2  s. c  om*/
    assertEquals("dataStreams:ds1", json.getString("@id"));
    assertEquals("My DS", json.getString("name"));
    JSONArray fa = json.getJSONArray("fields");
    assertEquals(1, fa.length());
    JSONObject f = fa.getJSONObject(0);
    assertEquals("dataStreams:ds1:fields:field1", f.getString("@id"));
    assertEquals("test", f.getString("name"));
    assertNotNull(f.getJSONObject("variable"));
    assertEquals("hubs:local:variables:plugin1:device1:var1", f.getJSONObject("variable").getString("@id"));
    fa = json.getJSONArray("tags");
    assertTrue("tag1".equals(json.getJSONArray("tags").getString(0))
            || "tag2".equals(json.getJSONArray("tags").getString(0)));
    assertTrue("tag1".equals(json.getJSONArray("tags").getString(1))
            || "tag2".equals(json.getJSONArray("tags").getString(1)));
    assertEquals(2, fa.length());
}