Example usage for org.json JSONObject optJSONObject

List of usage examples for org.json JSONObject optJSONObject

Introduction

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

Prototype

public JSONObject optJSONObject(String key) 

Source Link

Document

Get an optional JSONObject associated with a key.

Usage

From source file:com.ammobyte.radioreddit.api.GetSongInfo.java

@Override
protected Boolean doInBackground(String... params) {
    final String cookie = params[0]; // This will be null if not logged in

    // Prepare GET with cookie, execute it, parse response as JSON
    JSONObject response = null;
    try {//w w w  . j  a v  a  2  s. c  om
        final HttpClient httpClient = new DefaultHttpClient();
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("url", mSong.reddit_url));
        final HttpGet httpGet = new HttpGet(
                "http://www.reddit.com/api/info.json?" + URLEncodedUtils.format(nameValuePairs, "utf-8"));
        if (cookie != null) {
            // Using HttpContext, CookieStore, and friends didn't work
            httpGet.setHeader("Cookie", "reddit_session=" + cookie);
        }
        httpGet.setHeader("User-Agent", RedditApi.USER_AGENT);
        final HttpResponse httpResponse = httpClient.execute(httpGet);
        response = new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
    } catch (UnsupportedEncodingException e) {
        Log.i(RedditApi.TAG, "UnsupportedEncodingException while getting song info", e);
    } catch (ClientProtocolException e) {
        Log.i(RedditApi.TAG, "ClientProtocolException while getting song info", e);
    } catch (IOException e) {
        Log.i(RedditApi.TAG, "IOException while getting song info", e);
    } catch (ParseException e) {
        Log.i(RedditApi.TAG, "ParseException while getting song info", e);
    } catch (JSONException e) {
        Log.i(RedditApi.TAG, "JSONException while getting song info", e);
    }

    // Check for failure
    if (response == null) {
        Log.i(RedditApi.TAG, "Response is null");
        return false;
    }

    // Get the info we want
    final JSONObject data1 = response.optJSONObject("data");
    if (data1 == null) {
        Log.i(RedditApi.TAG, "First data is null");
        return false;
    }
    final String modhash = data1.optString("modhash", "");
    if (modhash.length() > 0) {
        mService.setModhash(modhash);
    }
    final JSONArray children = data1.optJSONArray("children");
    if (children == null) {
        Log.i(RedditApi.TAG, "Children is null");
        return false;
    }
    final JSONObject child = children.optJSONObject(0);
    if (child == null) {
        // This is common if the song hasn't been submitted to reddit yet
        // so we intentionally don't log this case
        return false;
    }
    final String kind = child.optString("kind");
    if (kind == null) {
        Log.i(RedditApi.TAG, "Kind is null");
        return false;
    }
    final JSONObject data2 = child.optJSONObject("data");
    if (data2 == null) {
        Log.i(RedditApi.TAG, "Second data is null");
        return false;
    }
    final String id = data2.optString("id");
    if (id == null) {
        Log.i(RedditApi.TAG, "Id is null");
        return false;
    }
    final int score = data2.optInt("score");
    Boolean likes = null;
    if (!data2.isNull("likes")) {
        likes = data2.optBoolean("likes");
    }
    final boolean saved = data2.optBoolean("saved");

    // Modify song with collected info
    if (kind != null && id != null) {
        mSong.reddit_id = kind + "_" + id;
    } else {
        mSong.reddit_id = null;
    }
    mSong.upvoted = (likes != null && likes == true);
    mSong.downvoted = (likes != null && likes == false);
    mSong.votes = score;
    mSong.saved = saved;

    return true;
}

From source file:com.facebook.internal.Utility.java

private static FetchedAppSettings parseAppSettingsFromJSON(String applicationId, JSONObject settingsJSON) {
    FetchedAppSettings result = new FetchedAppSettings(
            settingsJSON.optBoolean(APP_SETTING_SUPPORTS_IMPLICIT_SDK_LOGGING, false),
            settingsJSON.optString(APP_SETTING_NUX_CONTENT, ""),
            settingsJSON.optBoolean(APP_SETTING_NUX_ENABLED, false),
            parseDialogConfigurations(settingsJSON.optJSONObject(APP_SETTING_DIALOG_CONFIGS)));

    fetchedAppSettings.put(applicationId, result);

    return result;
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitTest.java

protected static void assertGitSectionExists(JSONObject json) {
    JSONObject gitSection = json.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);//from  ww  w  .j a va  2s.co m
    assertNotNull(gitSection.optString(GitConstants.KEY_STATUS, null));
    assertNotNull(gitSection.optString(GitConstants.KEY_DIFF, null));
    assertNotNull(gitSection.optString(GitConstants.KEY_INDEX, null));
    assertNotNull(gitSection.optString(GitConstants.KEY_HEAD, null));
    assertNotNull(gitSection.optString(GitConstants.KEY_REMOTE, null));
    assertNotNull(gitSection.optString(GitConstants.KEY_TAG, null));
    assertNotNull(gitSection.optString(GitConstants.KEY_CLONE, null));
}

From source file:com.joyfulmongo.db.QueryConditionFilterRelation.java

private JSONObject getRelatedTo() {
    if (relatedTo == null) {
        JSONObject constraints = origBuilder.getConstraints();
        relatedTo = constraints.optJSONObject(S_KEY);
        if (relatedTo == null) {
            throw new IllegalArgumentException(
                    "The original builder constraint is not a relatedTo constraints");
        }/*from   w w w .j ava2 s .  c o m*/
    }
    return relatedTo;
}

From source file:edu.asu.bscs.csiebler.waypointapplication.WaypointServerStub.java

/**
 *
 * @param wpName//www  .  j  a va 2 s .c o m
 * @return
 */
public Waypoint get(String wpName) {
    Waypoint result = null;

    try {
        String jsonStr = this.packageWaypointCall("get", wpName, null);
        debug("sending: " + jsonStr);
        String resString = server.call(jsonStr);
        debug("got back: " + resString);
        JSONObject res = new JSONObject(resString);
        JSONObject resObj = res.optJSONObject("result");
        result = new Waypoint(resObj);
    } catch (Exception ex) {
        System.out.println("exception in rpc call to get: " + ex.getMessage());
    }

    return result;
}

From source file:com.connectsdk.cordova.JSCommandDispatcher.java

@CommandMethod
public void launcher_launchApp(JSCommand command, JSONObject args) throws JSONException {
    String appId = args.getString("appId");
    JSONObject params = args.optJSONObject("params");

    AppInfo appInfo = new AppInfo();
    appInfo.setId(appId);//from w  w  w  .j a  va 2 s .  c o m

    device.getLauncher().launchAppWithInfo(appInfo, params, command.getAppLaunchListener());
}

From source file:com.connectsdk.cordova.JSCommandDispatcher.java

@CommandMethod
public void webAppLauncher_launchWebApp(JSCommand command, JSONObject args) throws JSONException {
    String webAppId = args.getString("webAppId");
    JSONObject params = args.optJSONObject("params");

    if (params != null && device.hasCapability(WebAppLauncher.Launch_Params))
        device.getWebAppLauncher().launchWebApp(webAppId, params, command.getWebAppLaunchListener());
    else/* ww w .ja v a  2  s.  c  o m*/
        device.getWebAppLauncher().launchWebApp(webAppId, command.getWebAppLaunchListener());
}

From source file:com.connectsdk.cordova.JSCommandDispatcher.java

void showToast(JSCommand command, JSONObject args, boolean clickable) throws JSONException {
    String message = args.getString("message");
    JSONObject options = args.optJSONObject("options");

    String url = null;/*from w w w. j a  v a 2s .c  om*/
    String appId = null;
    String iconData = null;
    String iconExtension = null;
    JSONObject params = null;

    if (options != null) {
        iconData = options.optString("iconData");
        iconExtension = options.optString("iconExtension");

        if (clickable) {
            url = options.optString("url");
            appId = options.optString("appId");
            params = options.optJSONObject("params");
        }
    }

    if (clickable) {
        if (url != null) {
            device.getToastControl().showClickableToastForURL(message, url, iconData, iconExtension,
                    command.getResponseListener());
        } else if (appId != null) {
            AppInfo appInfo = new AppInfo();
            appInfo.setId(appId);
            device.getToastControl().showClickableToastForApp(message, appInfo, params, iconData, iconExtension,
                    command.getResponseListener());
        } else {
            command.error("toast options must include url or appId when showing a clickable toast");
        }
    } else {
        device.getToastControl().showToast(message, iconData, iconExtension, command.getResponseListener());
    }
}

From source file:com.norman0406.slimgress.API.Interface.Handshake.java

public Handshake(JSONObject json) throws JSONException {
    JSONObject result = json.getJSONObject("result");

    String pregameStatus = result.getJSONObject("pregameStatus").getString("action");
    if (pregameStatus.equals("CLIENT_MUST_UPGRADE"))
        mPregameStatus = PregameStatus.ClientMustUpgrade;
    else if (pregameStatus.equals("NO_ACTIONS_REQUIRED"))
        mPregameStatus = PregameStatus.NoActionsRequired;
    else/*from   ww w. j  a  v a  2s  . c o m*/
        throw new RuntimeException("unknown pregame status " + pregameStatus);

    mServerVersion = result.getString("serverVersion");

    // get player entity
    mNickname = result.optString("nickname");
    JSONArray playerEntity = result.optJSONArray("playerEntity");
    if (playerEntity != null)
        mAgent = new Agent(playerEntity, mNickname);

    mXSRFToken = result.optString("xsrfToken");

    // get knobs
    JSONObject knobs = result.optJSONObject("initialKnobs");
    if (knobs != null)
        mKnobs = new KnobsBundle(knobs);
}

From source file:com.facebook.share.internal.LikeActionController.java

private static LikeActionController deserializeFromJson(String controllerJsonString) {
    LikeActionController controller;//from   www  .j av a  2  s  . c  o  m

    try {
        JSONObject controllerJson = new JSONObject(controllerJsonString);
        int version = controllerJson.optInt(JSON_INT_VERSION_KEY, -1);
        if (version != LIKE_ACTION_CONTROLLER_VERSION) {
            // Don't attempt to deserialize a controller that might be serialized differently
            // than expected.
            return null;
        }

        String objectId = controllerJson.getString(JSON_STRING_OBJECT_ID_KEY);
        int objectTypeInt = controllerJson.optInt(JSON_INT_OBJECT_TYPE_KEY,
                LikeView.ObjectType.UNKNOWN.getValue());

        controller = new LikeActionController(objectId, LikeView.ObjectType.fromInt(objectTypeInt));

        // Make sure to default to null and not empty string, to keep the logic elsewhere
        // functioning properly.
        controller.likeCountStringWithLike = controllerJson.optString(JSON_STRING_LIKE_COUNT_WITH_LIKE_KEY,
                null);
        controller.likeCountStringWithoutLike = controllerJson
                .optString(JSON_STRING_LIKE_COUNT_WITHOUT_LIKE_KEY, null);
        controller.socialSentenceWithLike = controllerJson.optString(JSON_STRING_SOCIAL_SENTENCE_WITH_LIKE_KEY,
                null);
        controller.socialSentenceWithoutLike = controllerJson
                .optString(JSON_STRING_SOCIAL_SENTENCE_WITHOUT_LIKE_KEY, null);
        controller.isObjectLiked = controllerJson.optBoolean(JSON_BOOL_IS_OBJECT_LIKED_KEY);
        controller.unlikeToken = controllerJson.optString(JSON_STRING_UNLIKE_TOKEN_KEY, null);

        JSONObject analyticsJSON = controllerJson.optJSONObject(JSON_BUNDLE_FACEBOOK_DIALOG_ANALYTICS_BUNDLE);
        if (analyticsJSON != null) {
            controller.facebookDialogAnalyticsBundle = BundleJSONConverter.convertToBundle(analyticsJSON);
        }
    } catch (JSONException e) {
        Log.e(TAG, "Unable to deserialize controller from JSON", e);
        controller = null;
    }

    return controller;
}