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.samsung.locator.SamiActivity.java

/**
 * Connects to /live websocket if necessary
 *///from   w ww  . java2 s  .  com
private void connectLiveWebsocket() {
    if (live == null) {
        live = new Websocket();
    }
    if (!live.isConnected() && !live.isConnecting()) {
        live.connect(Config.LIVE_URL, new WebsocketEvents() {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                setLiveText("Live connected to from SAMI!");
            }

            @Override
            public void onMessage(String message) {
                setLiveText("Live onMessage(): " + message);
                try {
                    JSONObject json = new JSONObject(message);
                    JSONObject dataNode = json.optJSONObject("data");
                    if (dataNode != null) {
                        lastLat = dataNode.getString("lat");
                        lastLng = dataNode.getString("lng");
                    }
                } catch (JSONException e) {
                    // This message doesn't contain data node, might be a ping.
                }
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                setLiveText("Live closed: " + code);
            }

            @Override
            public void onError(Exception ex) {
                setLiveText("Live error: " + ex.getMessage());
            }
        });
    }
}

From source file:com.vk.sdkweb.api.model.VKList.java

/**
 * Fills list according with data in {@code from}.
 * @param from an object that represents a list adopted in accordance with VK API format. You can use null.
 * @param clazz class represents a model that has a public constructor with {@link org.json.JSONObject} argument.
 */// w w  w  . j  a v  a 2 s .com
public void fill(JSONObject from, Class<? extends T> clazz) {
    if (from.has("response")) {
        JSONArray array = from.optJSONArray("response");
        if (array != null) {
            fill(array, clazz);
        } else {
            fill(from.optJSONObject("response"), clazz);
        }
    } else {
        fill(from, new ReflectParser<T>(clazz));
    }
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java

/*******************************************************************************************
 * Sends a POST request to Google's servers and retrieves a JSONArray with all user 
 * playlists. The JSONArray contains the fields of the playlist such as "id", "name", 
 * "type", etc. (for a list of all response fields, see MobileClientPlaylistsSchema.java).
 * //from  www  . j  a v  a2 s .co  m
 * @return A JSONArray object that contains all user playlists and their fields.
 * @param context The context to use while retrieving user playlists.
 *******************************************************************************************/
public static final JSONArray getUserPlaylistsMobileClient(Context context)
        throws JSONException, IllegalArgumentException {

    JSONObject jsonRequestParams = new JSONObject();
    JSONArray playlistsJSONArray = new JSONArray();

    jsonRequestParams.put("max-results", 250);
    jsonRequestParams.put("start-token", "0");

    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context,
            "https://www.googleapis.com/sj/v1.1/playlistfeed?alt=json&hl=en_US&tier=basic",
            new ByteArrayEntity(jsonRequestParams.toString().getBytes()), "application/json");

    JSONObject resultJSONObject = new JSONObject(result);
    JSONObject dataJSONObject = new JSONObject();

    if (resultJSONObject != null) {
        dataJSONObject = resultJSONObject.optJSONObject("data");
    }

    if (dataJSONObject != null) {
        playlistsJSONArray = dataJSONObject.getJSONArray("items");
    }

    return playlistsJSONArray;
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java

/******************************************************************************************
 * Retrieves a JSONAray with all songs in <i><b>every</b></i> playlist. The JSONArray 
 * contains the fields of the songs such as "id", "clientId", "trackId", etc. (for a list 
 * of all fields, see MobileClientPlaylistEntriesSchema.java). 
 * /*www  .  j ava  2 s . c o  m*/
 * @deprecated This method is fully functional. However, there are issues with retrieving 
 * the correct playlist entryIds. Specifically, the entryIds do not seem to work with 
 * reordering playlists via the MobileClient mutations protocol. 
 * 
 * @return A JSONArray object that contains all songs and their fields within every playlist. 
 * @param context The context to use while retrieving songs from the playlist.
 ******************************************************************************************/
public static final JSONArray getPlaylistEntriesMobileClient(Context context)
        throws JSONException, IllegalArgumentException {

    JSONArray playlistEntriesJSONArray = new JSONArray();
    JSONObject jsonRequestParams = new JSONObject();

    jsonRequestParams.put("max-results", 10000);
    jsonRequestParams.put("start-token", "0");

    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context,
            "https://www.googleapis.com/sj/v1.1/plentryfeed?alt=json&hl=en_US&tier=basic",
            new ByteArrayEntity(jsonRequestParams.toString().getBytes()), "application/json");

    JSONObject resultJSONObject = new JSONObject(result);
    JSONObject dataJSONObject = new JSONObject();

    if (resultJSONObject != null) {
        dataJSONObject = resultJSONObject.optJSONObject("data");
    }

    if (dataJSONObject != null) {
        playlistEntriesJSONArray = dataJSONObject.getJSONArray("items");
    }

    return playlistEntriesJSONArray;
}

From source file:com.sina.weibo.sdk_lib.openapi.models.Favorite.java

public static Favorite parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }/*from w  w  w  .  j a  v a  2s.c om*/

    Favorite favorite = new Favorite();
    favorite.status = Status.parse(jsonObject.optJSONObject("status"));
    favorite.favorited_time = jsonObject.optString("favorited_time");

    JSONArray jsonArray = jsonObject.optJSONArray("tags");
    if (jsonArray != null && jsonArray.length() > 0) {
        int length = jsonArray.length();
        favorite.tags = new ArrayList<Tag>(length);
        for (int ix = 0; ix < length; ix++) {
            favorite.tags.add(Tag.parse(jsonArray.optJSONObject(ix)));
        }
    }

    return favorite;
}

From source file:com.melniqw.instagramsdk.Image.java

public static Image fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    Image image = new Image();
    JSONObject lowResolutionJSON = o.optJSONObject("low_resolution");
    image.lowResolution.url = lowResolutionJSON.optString("url");
    image.lowResolution.width = lowResolutionJSON.optInt("width");
    image.lowResolution.height = lowResolutionJSON.optInt("height");
    JSONObject standartResolutionJSON = o.optJSONObject("standard_resolution");
    image.standartResolution.url = standartResolutionJSON.optString("url");
    image.standartResolution.width = standartResolutionJSON.optInt("width");
    image.standartResolution.height = standartResolutionJSON.optInt("height");
    JSONObject thumbnailJSON = o.optJSONObject("thumbnail");
    image.thumbnail.url = thumbnailJSON.optString("url");
    image.thumbnail.width = thumbnailJSON.optInt("width");
    image.thumbnail.height = thumbnailJSON.optInt("height");
    return image;
}

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

@Test
public void testPullRemote() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);

    // clone1: create
    JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null);
    IPath clonePath1 = getClonePath(workspaceId, project1);
    JSONObject clone1 = clone(clonePath1);
    String cloneContentLocation1 = clone1.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
    String cloneLocation1 = clone1.getString(ProtocolConstants.KEY_LOCATION);
    String branchesLocation1 = clone1.getString(GitConstants.KEY_BRANCH);

    // get project1 metadata
    WebRequest request = getGetRequest(project1.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project1 = new JSONObject(response.getText());
    JSONObject gitSection1 = project1.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection1);//from  w w  w  .j a  v a  2s  .c o  m
    String gitRemoteUri1 = gitSection1.getString(GitConstants.KEY_REMOTE);

    // clone1: branch 'a'
    Repository db1 = getRepositoryForContentLocation(cloneContentLocation1);
    Git git1 = new Git(db1);
    branch(branchesLocation1, "a");

    // clone1: push all
    // TODO: replace with REST API when bug 339115 is fixed
    git1.push().setPushAll().call();

    // clone2
    JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null);
    IPath clonePath2 = getClonePath(workspaceId, project2);
    JSONObject clone2 = clone(clonePath2);
    String cloneLocation2 = clone2.getString(ProtocolConstants.KEY_LOCATION);

    // get project2 metadata
    request = getGetRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project2 = new JSONObject(response.getText());
    JSONObject gitSection2 = project2.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection2);
    String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE);

    // clone1: switch to 'a'
    assertBranchExist(git1, "a");
    checkoutBranch(cloneLocation1, "a");

    // clone1: change, add, commit
    JSONObject testTxt1 = getChild(project1, "test.txt");
    modifyFile(testTxt1, "branch 'a' change");
    addFile(testTxt1);
    commitFile(testTxt1, "incoming branch 'a' commit", false);

    // clone1: push
    ServerStatus pushStatus = push(gitRemoteUri1, 2, 0, "a", Constants.HEAD, false);
    assertTrue(pushStatus.isOK());

    // clone1: switch to 'master'
    checkoutBranch(cloneLocation1, Constants.MASTER);

    // clone1: change
    testTxt1 = getChild(project1, "test.txt");
    modifyFile(testTxt1, "branch 'master' change");
    addFile(testTxt1);
    commitFile(testTxt1, "incoming branch 'master' commit", false);

    // clone1: push
    push(gitRemoteUri1, 2, 0, Constants.MASTER, Constants.HEAD, false);

    // clone2: get remote details
    JSONObject aDetails = getRemoteBranch(gitRemoteUri2, 2, 1, "a");
    String aOldRefId = aDetails.getString(ProtocolConstants.KEY_ID);
    JSONObject masterDetails = getRemoteBranch(gitRemoteUri2, 2, 0, Constants.MASTER);
    String masterOldRefId = masterDetails.getString(ProtocolConstants.KEY_ID);

    // clone2: pull
    pull(cloneLocation2);

    // clone2: check for new content on 'a'
    masterDetails = getRemoteBranch(gitRemoteUri2, 2, 1, "a");
    String newRefId = masterDetails.getString(ProtocolConstants.KEY_ID);
    assertFalse(aOldRefId.equals(newRefId));

    // clone2: assert nothing new on 'master'
    masterDetails = getRemoteBranch(gitRemoteUri2, 2, 0, Constants.MASTER);
    newRefId = masterDetails.getString(ProtocolConstants.KEY_ID);
    assertFalse(masterOldRefId.equals(newRefId));

    // make sure the change has been pulled into the current branch
    JSONObject testTxt2 = getChild(project2, "test.txt");
    assertEquals("branch 'master' change", getFileContent(testTxt2));
}

From source file:com.tonikorin.cordova.plugin.LocationProvider.LocationService.java

private void handleLocationQuery(JSONObject messageIn, String time) throws JSONException, IOException {
    Log.d(TAG, "Handle location query...");
    String ownName = config.optString("member", "");
    JSONObject teams = config.optJSONObject("teams");
    String teamName;/*w w w  .j  a  v  a  2 s. c om*/
    String teamPassword;
    String teamHost;
    JSONObject team = null;
    if (teams != null)
        team = teams.optJSONObject(messageIn.optString("teamId"));
    if (team != null) {
        teamName = team.optString("name", "");
        teamPassword = team.optString("password", "");
        ownName = team.optString("member", ownName);
        teamHost = team.optString("host", "");
    } else
        return; // => URI hanging in PostServer
    String msgType = messageIn.optString("messageType", LOCATE);
    // Create Messaging Server interface
    String messageUrl = config.optString("messageUrl", "").replace("{host}", teamHost);
    MessageServer msgServer = new MessageServer(ownName, teamName, teamPassword, messageUrl);
    if (messageIn.optString("memberName").equals(ownName)) {
        updateLocateHistory(messageIn, true, msgType, time);
        msgServer.post(RESERVED);
        SystemClock.sleep(5000);// 5 sec delay
        String pushUrl = config.optString("pushUrl", "").replace("{host}", teamHost);
        msgServer.updatePushToken(ownName, teamName, config.optString("token", ""), pushUrl);
        return;
    }
    // Read extra team configuration (e.g. icon and schedule)
    TeamConfig cTeam = new TeamConfig(config, teamName);
    // Store details about location query
    updateLocateHistory(messageIn, cTeam.isBlocked(), msgType, time);
    if (cTeam.isBlocked())
        msgServer.addBlockedField();
    msgServer.post(ALIVE);
    if (cTeam.isBlocked() || CHAT.equals(msgType))
        return; // skip giving your location
    try {
        //Log.d(TAG, "myContext: " + myContext.getPackageName());
        new MyLocation(myContext, myLocationResult, messageIn.optInt("accuracy", 50),
                config.optInt("timeout", 60)).start();
        JSONObject location = myLocationResult.getJsonLocation();
        //Log.d(TAG, "Background position accuracy: " + location.optInt("accuracy"));
        if (cTeam.getIcon() != null)
            msgServer.addIconField(cTeam.getIcon());
        msgServer.post(POSITION, location.toString());
    } catch (Exception e) {
        Log.e(TAG, "LocationProvider exception ", e);
        msgServer.post(FAILURE, e.getMessage());
    }
    Log.d(TAG, "Handle location query...completed!");
}

From source file:ee.vvk.ivotingverification.util.JSONParser.java

private void parseJsonTexts(JSONObject json) throws JSONException {
    texts = json.optJSONObject(TAG_TEXTS);
    if (texts.length() > 0) {
        C.loading = texts.optString("loading", C.loading);
        C.welcomeMessage = texts.optString("welcome_message", C.welcomeMessage);
        C.lblVote = texts.optString("lbl_vote", C.lblVote);
        C.lblVoteTxt = texts.optString("lbl_vote_txt", C.lblVoteTxt);
        C.btnNext = texts.optString("btn_next", C.btnNext);
        C.btnMore = texts.optString("btn_more", C.btnMore);
        C.btnOk = texts.optString("btn_ok", C.btnOk);
        C.btnPacketData = texts.optString("btn_packet_data", C.btnPacketData);
        C.btnWifi = texts.optString("btn_wifi", C.btnWifi);
        C.btnVerify = texts.optString("btn_verify", C.btnVerify);
        C.lblChoice = texts.optString("lbl_choice", C.lblChoice);
        C.lblCloseTimeout = texts.optString("lbl_close_timeout", C.lblCloseTimeout);
        C.notificationTitle = texts.optString("notification_title", C.notificationTitle);
        C.notificationMessage = texts.optString("notification_message", C.notificationMessage);
    }/*from   ww w . jav  a  2  s  .  c o  m*/
}

From source file:ee.vvk.ivotingverification.util.JSONParser.java

private void parseJsonErrors(JSONObject json) throws JSONException {
    errors = json.optJSONObject(TAG_ERRORS);
    if (texts.length() > 0) {
        C.noNetworkMessage = errors.optString("no_network_message", C.noNetworkMessage);
        C.problemQrCodeMessage = errors.optString("problem_qrcode_message", C.problemQrCodeMessage);
        C.badServerResponseMessage = errors.optString("bad_server_response_message",
                C.badServerResponseMessage);
        C.badVerificationMessage = errors.optString("bad_verification_message", C.badVerificationMessage);
    }//  w  w  w. j ava  2s.  c o  m
}