List of usage examples for org.json JSONArray length
public int length()
From source file:com.inductiveautomation.reporting.examples.datasource.common.RestJsonDataSource.java
/** * Creates and returns {@link Dataset} with String column types from a {@link JSONArray}. Returns empty if no data * was found and an exception was not thrown. *//*from w w w. j ava 2s . c o m*/ private Dataset createDatasetFromJSONArray(JSONArray jsonArray) throws JSONException { Dataset ds = null; if (jsonArray.length() >= 1) { // JSON objects in an array may not have values for each key, so make sure we // get the full keyset JSONObject reference = findReferenceObjectIndex(jsonArray); // get column names from the reference object List<String> colNames = new ArrayList<>(); Iterator keys = reference.keys(); while (keys.hasNext()) { colNames.add(keys.next().toString()); } // now start building dataset to pass into report engine DatasetBuilder builder = new DatasetBuilder(); builder.colNames(colNames.toArray(new String[colNames.size()])); // set the column types. We're using all strings in this example, but we could be // checking for numeric types and setting different column types to enable calculations Class[] types = new Class[colNames.size()]; for (int i = 0; i < types.length; i++) { types[i] = String.class; } builder.colTypes(types); // now create rows for each json list value for (int row = 0; row < jsonArray.length(); row++) { String[] rowData = new String[colNames.size()]; for (int col = 0; col < colNames.size(); col++) { try { rowData[col] = jsonArray.getJSONObject(row).get(colNames.get(col)).toString(); } catch (JSONException e) { // ignore because it just means this object didn't have our key } } builder.addRow(rowData); } ds = builder.build(); } return ds != null ? ds : new BasicDataset(); }
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 w w . j a va 2s .c om 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); }//ww w . j av a2 s . c o 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);/*from www . j a va 2 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 w w.j a 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
/** * ??? /*w w w . ja va 2 s. com*/ * {"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
/** * ??? //ww w .j a v a2s.c o 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.gmail.boiledorange73.ut.map.MapActivityBase.java
/** * Called when JS sends the message.//from w ww. j av a 2 s.co 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.microsoft.research.webngram.service.impl.LookupServiceImpl.java
@Override public List<Double> getConditionalProbabilities(String authorizationToken, String modelUrn, List<String> phrases) { try {//from w ww. ja v a 2s .c o m List<Double> probabilities = new ArrayList<Double>(); NgramServiceApiUrlBuilder urlBuilder = createNgramServiceApiUrlBuilder( NgramServiceApiUrls.GET_CONDITIONAL_PROBABILITIES_URL); String apiUrl = urlBuilder.withField(ParameterNames.MODEL_URL, modelUrn) .withParameter(ParameterNames.USER_TOKEN, authorizationToken).buildUrl(); JSONArray array = new JSONArray( convertStreamToString(callApiMethod(apiUrl, getPostBody(phrases), null, "POST", 200))); for (int i = 0; i < array.length(); i++) { probabilities.add(array.getDouble(i)); } return probabilities; } catch (Exception e) { throw new NgramServiceException("An error occurred while getting conditional probabilities.", e); } }
From source file:com.microsoft.research.webngram.service.impl.LookupServiceImpl.java
@Override public List<String> getModels() { try {/*from w w w . ja v a 2 s .co m*/ List<String> models = new ArrayList<String>(); NgramServiceApiUrlBuilder urlBuilder = createNgramServiceApiUrlBuilder(NgramServiceApiUrls.LOOKUP_URL); String apiUrl = urlBuilder.buildUrl(); JSONArray array = new JSONArray(convertStreamToString(callApiGet(apiUrl))); for (int i = 0; i < array.length(); i++) { models.add(array.getString(i)); } return models; } catch (Exception e) { throw new NgramServiceException("An error occurred while getting models.", e); } }