Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

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

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

From source file:org.aosutils.android.youtube.YtApiClientV3.java

private static SearchResultIds searchYtIds(String query, String type, int maxResults, String pageToken,
        String apiKey) throws IOException, JSONException {
    ArrayList<String> ids = new ArrayList<>();

    Builder uriBuilder = new Uri.Builder().scheme("https").authority("www.googleapis.com")
            .path("/youtube/v3/search").appendQueryParameter("key", apiKey).appendQueryParameter("part", "id")
            .appendQueryParameter("order", "relevance")
            .appendQueryParameter("maxResults", Integer.toString(maxResults)).appendQueryParameter("q", query);

    if (type != null) {
        uriBuilder.appendQueryParameter("type", type);
    }//from   w ww  .  j ava2  s . c o m
    if (pageToken != null) {
        uriBuilder.appendQueryParameter("pageToken", pageToken);
    }

    String uri = uriBuilder.build().toString();
    String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT);

    JSONObject jsonObject = new JSONObject(output);

    String nextPageToken = jsonObject.has("nextPageToken") ? jsonObject.getString("nextPageToken") : null;
    JSONArray items = jsonObject.getJSONArray("items");

    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);
        JSONObject id = item.getJSONObject("id");

        ids.add(id.has("videoId") ? id.getString("videoId") : id.getString("playlistId"));
    }

    SearchResultIds searchResult = new SearchResultIds(ids, nextPageToken);

    return searchResult;
}

From source file:org.aosutils.android.youtube.YtApiClientV3.java

private static SearchResultIds playlistVideoIds(String playlistId, int maxResults, String pageToken,
        String apiKey) throws IOException, JSONException {
    ArrayList<String> ids = new ArrayList<>();

    Builder uriBuilder = new Uri.Builder().scheme("https").authority("www.googleapis.com")
            .path("/youtube/v3/playlistItems").appendQueryParameter("key", apiKey)
            .appendQueryParameter("part", "id,snippet")
            .appendQueryParameter("maxResults", Integer.toString(maxResults))
            .appendQueryParameter("playlistId", playlistId);

    if (pageToken != null) {
        uriBuilder.appendQueryParameter("pageToken", pageToken);
    }//from w  w  w  .  ja v a 2 s.co  m

    String uri = uriBuilder.build().toString();
    String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT);

    JSONObject jsonObject = new JSONObject(output);

    String nextPageToken = jsonObject.has("nextPageToken") ? jsonObject.getString("nextPageToken") : null;
    JSONArray items = jsonObject.getJSONArray("items");

    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);
        JSONObject snippet = item.getJSONObject("snippet");

        JSONObject resourceId = snippet.getJSONObject("resourceId");
        ids.add(resourceId.getString("videoId"));
    }

    SearchResultIds searchResult = new SearchResultIds(ids, nextPageToken);

    return searchResult;
}

From source file:org.aosutils.android.youtube.YtApiClientV3.java

public static ArrayList<YtPlaylist> getPlaylistInfo(Collection<String> playlistIds, String apiKey)
        throws IOException, JSONException {
    ArrayList<YtPlaylist> playlists = new ArrayList<>();

    String uri = new Uri.Builder().scheme("https").authority("www.googleapis.com").path("/youtube/v3/playlists")
            .appendQueryParameter("key", apiKey).appendQueryParameter("part", "id,snippet")
            .appendQueryParameter("id", TextUtils.join(",", playlistIds)).build().toString();

    String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT);
    JSONObject jsonObject = new JSONObject(output);

    JSONArray items = jsonObject.getJSONArray("items");
    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);

        String playlistId = item.getString("id");
        String title = item.getJSONObject("snippet").getString("title");
        String description = item.getJSONObject("snippet").getString("description");

        YtPlaylist playlist = new YtPlaylist(playlistId, title, description);
        playlists.add(playlist);/* www .ja va2 s  .  c  om*/
    }

    return playlists;
}

From source file:org.aosutils.android.youtube.YtApiClientV3.java

public static ArrayList<YtVideo> getVideoInfo(Collection<String> videoIds, String apiKey)
        throws IOException, JSONException {
    ArrayList<YtVideo> videos = new ArrayList<>();

    String uri = new Uri.Builder().scheme("https").authority("www.googleapis.com").path("/youtube/v3/videos")
            .appendQueryParameter("key", apiKey).appendQueryParameter("part", "id,snippet,contentDetails")
            .appendQueryParameter("id", TextUtils.join(",", videoIds)).build().toString();

    String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT);
    JSONObject jsonObject = new JSONObject(output);

    JSONArray items = jsonObject.getJSONArray("items");
    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);

        String videoId = item.getString("id");
        String title = item.getJSONObject("snippet").getString("title");
        String description = item.getJSONObject("snippet").getString("description");

        String durationStr = item.getJSONObject("contentDetails").getString("duration");

        int hours = !durationStr.contains("H") ? 0
                : Integer.parseInt(
                        durationStr.substring(durationStr.indexOf("PT") + 2, durationStr.indexOf("H")));
        int minutes = !durationStr.contains("M") ? 0
                : hours > 0/*from  w ww. ja v  a  2s  . com*/
                        ? Integer.parseInt(
                                durationStr.substring(durationStr.indexOf("H") + 1, durationStr.indexOf("M")))
                        : Integer.parseInt(
                                durationStr.substring(durationStr.indexOf("PT") + 2, durationStr.indexOf("M")));
        int seconds = !durationStr.contains("S") ? 0
                : minutes > 0
                        ? Integer.parseInt(
                                durationStr.substring(durationStr.indexOf("M") + 1, durationStr.indexOf("S")))
                        : hours > 0
                                ? Integer.parseInt(durationStr.substring(durationStr.indexOf("H") + 1,
                                        durationStr.indexOf("S")))
                                : Integer.parseInt(durationStr.substring(durationStr.indexOf("PT") + 2,
                                        durationStr.indexOf("S")));
        int duration = (hours * 60 * 60) + (minutes * 60) + seconds;

        boolean licensedContent = item.getJSONObject("contentDetails").getBoolean("licensedContent");

        YtVideo video = new YtVideo(videoId, title, description, duration);
        video.setIsLicensedContent(licensedContent);
        videos.add(video);
    }

    return videos;
}

From source file:com.abc.driver.MainActivity.java

/**
 * ??? /*from   w  w  w.j a  va  2 s .co m*/
 * {"result_code":"0","horders":[{"id":6,"shipper_username":
 * "\u674e\u674e\u90bb\u5c45\u5929",
 * "shipper_phone":"","shipper_date":"2015-03-15 00:00:00"
 * ,"shipper_address_code":"110000-110100-110101",
 * "consignee_username":"","consignee_phone"
 * :"","consignee_address_code":"110000-110100-110101",
 * "delivery_time":"0000-00-00 00:00:00"
 * ,"truck_type":"","truck_length":"","cargo_type":"CT1",
 * "cargo_volume":"\u6d4b\u8bd5",
 * "cargo_weight":"\u6d4b\u8bd5\u554a","horder_desc"
 * :"","user_id":9,"status":0, "created_at":"2015-03-15 03:30:50",
 * "updated_at":"2015-03-15 03:30:50"},}]}
 * 
 * @param jsonResult
 */
public void parseJson(JSONObject jsonResult) {
    HashMap<String, Object> mHorder;
    try {
        if (jsonResult.get("horders") != JSONObject.NULL) {
            JSONArray results = jsonResult.getJSONArray("horders");
            if (results.length() < CellSiteConstants.PAGE_COUNT) {
                mHorderTypes[mCurrRadioIdx].hasShowAllHorders = true;
            }

            for (int i = 0; i < results.length(); i++) {
                try {
                    JSONObject resultObj = (JSONObject) results.get(i);
                    mHorder = new HashMap<String, Object>();
                    mHorder.put(CellSiteConstants.SHIPPER_USERNAME,
                            resultObj.getString(CellSiteConstants.SHIPPER_USERNAME));
                    mHorder.put("horder_id", (resultObj).getString(CellSiteConstants.ID));
                    // TODO : 
                    int counter = 0;

                    mHorderTypes[mCurrRadioIdx].nHorders.add(mHorder);
                } catch (Exception e) {
                    mHasExceptionHorder = true;
                    continue;
                }

            }

        }

    } catch (JSONException e) {
        Log.d(TAG, "JSONException" + e.toString());

    }

}

From source file:com.abc.driver.MainActivity.java

/**
 * ??? /*from ww w .  j ava 2  s  .  co  m*/
 * {"result_code":"0","horders":[{"id":6,"shipper_username":
 * "\u674e\u674e\u90bb\u5c45\u5929",
 * "shipper_phone":"","shipper_date":"2015-03-15 00:00:00"
 * ,"shipper_address_code":"110000-110100-110101",
 * "consignee_username":"","consignee_phone"
 * :"","consignee_address_code":"110000-110100-110101",
 * "delivery_time":"0000-00-00 00:00:00"
 * ,"truck_type":"","truck_length":"","cargo_type":"CT1",
 * "cargo_volume":"\u6d4b\u8bd5",
 * "cargo_weight":"\u6d4b\u8bd5\u554a","horder_desc"
 * :"","user_id":9,"status":0, "created_at":"2015-03-15 03:30:50",
 * "updated_at":"2015-03-15 03:30:50"},}]}
 * 
 * @param jsonResult
 */
public void parseFHorderJson(JSONObject jsonResult) {
    HashMap<String, Object> mHorder;
    try {
        if (jsonResult.get("horders") != JSONObject.NULL) {
            JSONArray results = jsonResult.getJSONArray("horders");
            if (results.length() < CellSiteConstants.PAGE_COUNT) {
                mFHorderTypes.hasShowAllHorders = true;
            }

            for (int i = 0; i < results.length(); i++) {
                try {
                    JSONObject resultObj = (JSONObject) results.get(i);
                    JSONArray repliedDriversObj = null;
                    mHorder = new HashMap<String, Object>();

                    mHorder.put(CellSiteConstants.ALREADY_REPLIED, 0);
                    try {
                        // 1. ???repliedtag 1 ?0
                        // 2.
                        repliedDriversObj = resultObj.getJSONArray(CellSiteConstants.REPLIED_DRIVERS);
                        if (repliedDriversObj != null) {
                            for (int j = 0; j < repliedDriversObj.length(); j++) {
                                String driver_id = ((JSONObject) repliedDriversObj.get(i))
                                        .getString(CellSiteConstants.DRIVER_ID);
                                if (driver_id.equals("" + app.getUser().getId())) {
                                    mHorder.put(CellSiteConstants.ALREADY_REPLIED, 1);
                                    break;
                                }

                            }
                            mHorder.put(CellSiteConstants.REPLIED_DRIVERS_COUNT, repliedDriversObj.length());
                        }
                    } catch (Exception e) {

                    }

                    mHorder.put(CellSiteConstants.SHIPPER_USERNAME,
                            resultObj.getString(CellSiteConstants.SHIPPER_USERNAME));
                    mHorder.put(CellSiteConstants.HORDER_ID, (resultObj).getString(CellSiteConstants.ID));
                    mHorder.put(CellSiteConstants.SHIPPER_PHONE,
                            (resultObj).getString(CellSiteConstants.SHIPPER_PHONE));
                    mHorder.put(CellSiteConstants.USER_ID, (resultObj).getString(CellSiteConstants.USER_ID));

                    CityDBReader dbReader = new CityDBReader(this.getApplicationContext());
                    mHorder.put(CellSiteConstants.SHIPPER_ADDRESS_NAME, dbReader
                            .getNameFromCode((resultObj).getString(CellSiteConstants.SHIPPER_ADDRESS_CODE_IN)));
                    mHorder.put(CellSiteConstants.CONSIGNEE_ADDRESS_NAME, dbReader
                            .getNameFromCode((resultObj).getString(CellSiteConstants.CONSIGNEE_ADDRESS_CODE2)));
                    mHorder.put(CellSiteConstants.CARGO_TYPE,
                            (resultObj).getString(CellSiteConstants.CARGO_TYPE));
                    mHorder.put(CellSiteConstants.CARGO_WEIGHT,
                            (resultObj).getString(CellSiteConstants.CARGO_WEIGHT));
                    mHorder.put(CellSiteConstants.CARGO_VOLUME,
                            (resultObj).getString(CellSiteConstants.CARGO_VOLUME));
                    mHorder.put(CellSiteConstants.TRUCK_TYPE,
                            (resultObj).getString(CellSiteConstants.TRUCK_TYPE));
                    mHorder.put(CellSiteConstants.HORDER_STATUS,
                            (resultObj).getString(CellSiteConstants.STATUS));
                    mHorder.put(CellSiteConstants.SHIPPER_DATE,
                            (resultObj).getString(CellSiteConstants.SHIPPER_DATE));
                    mHorder.put(CellSiteConstants.HORDER_DESCRIPTION,
                            (resultObj).getString(CellSiteConstants.HORDER_DESCRIPTION));
                    mHorder.put(CellSiteConstants.SHIPPER_USERNAME,
                            (resultObj).getString(CellSiteConstants.SHIPPER_USERNAME));

                    // TODO :
                    int counter = 0;

                    mFHorderTypes.nHorders.add(mHorder);
                } catch (Exception e) {
                    mHasExceptionFHorder = true;
                    continue;
                }

            }

        }

    } catch (JSONException e) {
        Log.d(TAG, "JSONException" + e.toString());

    }

}

From source file:com.kkurahar.locationmap.JsonParserTask.java

@Override
protected String doInBackground(String... params) {

    String shortUrl = new String();
    HttpConnection con = new HttpConnection();
    // http?M?iGET?jJSON?iZ?kURL??j
    String jsonObj = con.doGet(createGetParam(params[0]));

    // GET?MJSONIuWFNg?uShortUrl?vl?o
    try {/*www  . ja  va  2 s .c om*/
        // ?ubit.ly?vdl
        JSONObject jsonObject = new JSONObject(jsonObj);
        JSONObject resultsObject = jsonObject.getJSONObject("results");
        JSONObject paramObject = resultsObject.getJSONObject(params[0]);
        shortUrl = paramObject.getString("shortUrl");

    } catch (JSONException e) {
        e.printStackTrace();
    }

    return shortUrl;
}

From source file:com.github.koraktor.steamcondenser.community.WebApiTest.java

@Test
public void testGetJSONDataFailed() throws Exception {
    String data = mock(String.class);
    spy(WebApi.class);
    doReturn(data).when(WebApi.class, "getJSON", "interface", "method", 2, null);
    JSONObject json = mock(JSONObject.class);
    JSONObject result = mock(JSONObject.class);
    when(json.getJSONObject("result")).thenReturn(result);
    when(result.getInt("status")).thenReturn(0);
    when(result.getString("statusDetail")).thenReturn("Error");
    whenNew(JSONObject.class).withParameterTypes(String.class).withArguments(data).thenReturn(json);

    this.exception.expect(WebApiException.class);
    this.exception
            .expectMessage("The Web API request failed with the following error: Error (status code: 0).");

    WebApi.getJSONData("interface", "method", 2);
}

From source file:com.gmail.boiledorange73.ut.map.MapActivityBase.java

/**
 * Called when JS sends the message.//from   w  w  w .j a  va2s. c o  m
 * 
 * @param bridge
 *            Receiver instance.
 * @param code
 *            The code name. This looks like the name of function.
 * @param message
 *            The message. This looks like the argument of function. This is
 *            usually expressed as JSON.
 */
@Override
public void onArriveMessage(JSBridge bridge, String code, String message) {
    if (code == null) {
    } else if (code.equals("onLoad")) {
        this.mMaptypeList = new ArrayList<ValueText<String>>();
        this.mLoaded = true;
        // executes queued commands.
        this.execute(null);
        JSONArray json = null;
        try {
            json = new JSONArray(message);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (json != null) {
            for (int n = 0; n < json.length(); n++) {
                JSONObject one = null;
                try {
                    one = json.getJSONObject(n);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (one != null) {
                    String id = null, name = null;
                    try {
                        id = one.getString("id");
                        name = one.getString("name");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (id != null && name != null) {
                        this.mMaptypeList.add(new ValueText<String>(id, name));
                    }
                }
            }
        }
        // restores map state (2013/08/07)
        if (this.mInternalMapState != null) {
            this.restoreMapState(this.mInternalMapState.id, this.mInternalMapState.lon,
                    this.mInternalMapState.lat, this.mInternalMapState.z);
            this.mInternalMapState = null;
        }
        // request to create menu items.
        this.invalidateOptionsMenuIfPossible();
    } else if (code.equals("getCurrentMapState")) {
        if (message == null || !(message.length() > 0)) {
            // DOES NOTHING
        } else {
            try {
                JSONObject json = new JSONObject(message);
                this.mInternalMapState = new MapState();
                this.mInternalMapState.id = json.getString("id");
                this.mInternalMapState.lat = json.getDouble("lat");
                this.mInternalMapState.lon = json.getDouble("lon");
                this.mInternalMapState.z = json.getInt("z");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        this.mWaitingForgetCurrentMapState = false;
    } else if (code.equals("getCurrentZoomState")) {
        if (message == null) {
            // DOES NOTHING
        } else {
            try {
                JSONObject json = new JSONObject(message);
                this.mZoomState = new ZoomState();
                this.mZoomState.minzoom = json.getInt("minzoom");
                this.mZoomState.maxzoom = json.getInt("maxzoom");
                this.mZoomState.currentzoom = json.getInt("currentzoom");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            this.mWaitingForgetCurrentZoomState = false;
        }
    } else if (code.equals("alert")) {
        // shows alert text.
        (new AlertDialog.Builder(this)).setTitle(this.getTitle()).setMessage(message != null ? message : "")
                .setCancelable(true).setPositiveButton(android.R.string.ok, null).show();
    }
}

From source file:com.facebook.login.LoginMethodHandler.java

private static String getUserIDFromSignedRequest(String signedRequest) throws FacebookException {
    if (signedRequest == null || signedRequest.isEmpty()) {
        throw new FacebookException("Authorization response does not contain the signed_request");
    }/*  w  ww . j  a v a 2 s  . c  o  m*/

    try {
        String[] signatureAndPayload = signedRequest.split("\\.");
        if (signatureAndPayload.length == 2) {
            byte[] data = Base64.decode(signatureAndPayload[1], Base64.DEFAULT);
            String dataStr = new String(data, "UTF-8");
            JSONObject jsonObject = new JSONObject(dataStr);
            return jsonObject.getString("user_id");
        }
    } catch (UnsupportedEncodingException ex) {
    } catch (JSONException ex) {
    }
    throw new FacebookException("Failed to retrieve user_id from signed_request");
}