Example usage for org.json JSONObject optString

List of usage examples for org.json JSONObject optString

Introduction

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

Prototype

public String optString(String key) 

Source Link

Document

Get an optional string associated with a key.

Usage

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

public static Favorite parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }//w ww. j av a2s .c o m

    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.aerhard.oxygen.plugin.dbtagger.util.JsonUtil.java

/**
 * Gets table headers from the JSON server response.
 * //w  w w .j  a v a  2  s. c o  m
 * @param responseJSON
 *            the JSON response
 * @return the headers
 */
private String[] getTableHeaders(JSONObject responseJSON) {
    String[] cols = null;
    try {
        JSONArray colsArray = responseJSON.getJSONArray("cols");
        cols = new String[colsArray.length()];
        JSONObject fieldObj;
        for (int i = 0; i < colsArray.length(); i++) {
            fieldObj = (JSONObject) colsArray.get(i);
            cols[i] = fieldObj.optString("name");
        }
    } catch (JSONException e) {
        workspace.showErrorMessage(i18n.getString("jsonUtil.columnNameError"));
    }
    return cols;
}

From source file:com.textuality.gpstats.GPlusSnowflake.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == GPS_REQUEST_CODE && resultCode == RESULT_OK) {
        mAccount = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
        get("https://www.googleapis.com/plus/v1/people/me", mAccount,
                "oauth2:https://www.googleapis.com/auth/plus.me", null, new ResponseHandler() {

                    @Override//from  ww  w . j a  va 2  s. c  o  m
                    public void handle(Response response) {
                        if (response.status != 200) {
                            barf(response);
                            return;
                        }
                        try {
                            JSONObject json = new JSONObject(new String(response.body));
                            mID = json.optString("id");
                            readFeedPage(null);
                        } catch (JSONException je) {
                            throw new RuntimeException(je);
                        }
                    }
                });
    }
}

From source file:de.knufficast.search.GPodderSearch.java

public void search(final String query, final BooleanCallback<List<Result>, String> callback) {
    runOnThread(new Runnable() {
        @Override//  w w w.j ava2s  . c om
        public void run() {
            String queryUrl = String.format(SEARCH_URL, URLEncoder.encode(query));
            HttpGet request = new HttpGet(queryUrl);
            try {
                List<Result> results = new ArrayList<Result>();
                JSONArray response = httpUtil.getJsonArray(request);
                int max = response.length();
                for (int i = 0; i < max; i++) {
                    JSONObject jsonResult = response.getJSONObject(i);
                    GPodderResult result = new GPodderResult();
                    result.website = jsonResult.optString("website");
                    result.description = jsonResult.optString("description");
                    result.title = jsonResult.optString("title");
                    result.feedUrl = jsonResult.optString("url");
                    result.imgUrl = jsonResult.optString("scaled_logo_url");
                    results.add(result);
                }
                callback.success(results);
            } catch (IOException e) {
                callback.fail(ERROR_CONNECTION);
            } catch (JSONException e) {
                callback.fail(ERROR_JSON);
            }
        }
    });
}

From source file:fr.openbike.android.io.RemoteStationsSyncHandler.java

/** {@inheritDoc} */
@Override/*from w w  w  .j av  a  2 s . c om*/
public Object parse(JSONObject jsonBikes, OpenBikeDBAdapter dbAdapter) throws JSONException, IOException {
    long version = jsonBikes.getLong(VERSION);
    String message = jsonBikes.optString(MESSAGE);
    if (version > mCurrentVersion) {
        return null;
    } else {
        JSONArray stations = jsonBikes.optJSONArray(STATIONS);
        if (stations != null) {
            if (dbAdapter.syncStations(stations)) { // Need
                // Update
                return null;
            }
        }
    }
    return message;
}

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.GitRevertTest.java

@Test
public void testRevert() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project/folder metadata
        WebRequest request = getGetRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject folder = new JSONObject(response.getText());

        JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

        JSONObject testTxt = getChild(folder, "test.txt");
        modifyFile(testTxt, "first line\nsec. line\nthird line\n");

        addFile(testTxt);//w ww  . jav  a 2  s  .co m

        commitFile(testTxt, "lines in test.txt", false);

        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(2, commitsArray.length());
        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        String toRevert = commit.getString(ProtocolConstants.KEY_NAME);

        // REVERT
        JSONObject revert = revert(gitHeadUri, toRevert);
        assertEquals("OK", revert.getString(GitConstants.KEY_RESULT));

        // new revert commit is present
        commitsArray = log(gitHeadUri);
        assertEquals(3, commitsArray.length());
        commit = commitsArray.getJSONObject(0);

        String revertMessage = commit.optString(GitConstants.KEY_COMMIT_MESSAGE);
        assertEquals(true, revertMessage != null);
        assertEquals(true, revertMessage.startsWith("Revert \"lines in test.txt\""));
    }
}

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

@Test
public void testRevertFailure() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project/folder metadata
        WebRequest request = getGetRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject folder = new JSONObject(response.getText());

        JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

        JSONObject testTxt = getChild(folder, "test.txt");
        modifyFile(testTxt, "first line\nsec. line\nthird line\n");

        addFile(testTxt);//from w w  w .  j  ava  2  s.  c  om

        commitFile(testTxt, "lines in test.txt", false);

        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(2, commitsArray.length());
        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        String toRevert = commit.getString(ProtocolConstants.KEY_NAME);
        modifyFile(testTxt, "first line\nsec. line\nthird line\nfourth line\n");
        addFile(testTxt);

        // REVERT
        JSONObject revert = revert(gitHeadUri, toRevert);
        assertEquals("FAILURE", revert.getString(GitConstants.KEY_RESULT));

        // there's no new revert commit
        commitsArray = log(gitHeadUri);
        assertEquals(2, commitsArray.length());
        commit = commitsArray.getJSONObject(0);

        String revertMessage = commit.optString(GitConstants.KEY_COMMIT_MESSAGE);
        assertEquals(true, revertMessage != null);
        assertEquals(false, revertMessage.startsWith("Revert \"lines in test.txt\""));
    }
}

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;//ww w  .  j  a  v a 2  s. co  m
    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:ezy.boost.update.UpdateInfo.java

private static UpdateInfo parse(JSONObject o) {
    UpdateInfo info = new UpdateInfo();
    if (o == null) {
        return info;
    }//  w ww.  j  av  a  2s .co  m
    info.hasUpdate = o.optBoolean("hasUpdate", false);
    if (!info.hasUpdate) {
        return info;
    }
    info.isSilent = o.optBoolean("isSilent", false);
    info.isForce = o.optBoolean("isForce", false);
    info.isAutoInstall = o.optBoolean("isAutoInstall", !info.isSilent);
    info.isIgnorable = o.optBoolean("isIgnorable", true);
    info.isPatch = o.optBoolean("isPatch", false);

    info.versionCode = o.optInt("versionCode", 0);
    info.versionName = o.optString("versionName");
    info.updateContent = o.optString("updateContent");

    info.url = o.optString("url");
    info.md5 = o.optString("md5");
    info.size = o.optLong("size", 0);

    if (!info.isPatch) {
        return info;
    }
    info.patchUrl = o.optString("patchUrl");
    info.patchMd5 = o.optString("patchMd5");
    info.patchSize = o.optLong("patchSize", 0);
    return info;
}