List of usage examples for org.json JSONObject getJSONArray
public JSONArray getJSONArray(String key) throws JSONException
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 ww w. ja v a2 s . c om 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);// w w w. jav a 2s . co m } 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// w w w.ja va 2 s .c o m ? 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
/** * ??? /* www . j av a2 s . c om*/ * {"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 w w w . j av a 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 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:feedme.controller.UpdateCategoryServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from ww w .j a v a 2 s . c om * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); String city = request.getParameter("city"); HashMap<String, Integer> cat = new DbHPOnLoad().getCategoriesByCity(city); try { JSONObject catObj = new JSONObject(); catObj.put("categorys", new JSONArray()); JSONArray cate = catObj.getJSONArray("categorys"); for (Map.Entry<String, Integer> entry : cat.entrySet()) { cate.put(new JSONObject().put("cat_id", entry.getValue()).put("cat_name", entry.getKey())); } response.setContentType("application/json"); PrintWriter writer = response.getWriter(); writer.print(catObj); response.getWriter().flush(); } catch (JSONException ex) { Logger.getLogger(OrderCompleteServlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.asd.littleprincesbeauty.data.SqlNote.java
public boolean setContent(JSONObject js) { try {/*www.j av a2s . com*/ JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { Log.w(TAG, "cannot set system folder"); } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { // for folder we can only update the snnipet and type String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : ""; if (mIsCreate || !mSnippet.equals(snippet)) { mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); } mSnippet = snippet; int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE; if (mIsCreate || mType != type) { mDiffNoteValues.put(NoteColumns.TYPE, type); } mType = type; } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID; if (mIsCreate || mId != id) { mDiffNoteValues.put(NoteColumns.ID, id); } mId = id; long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note.getLong(NoteColumns.ALERTED_DATE) : 0; if (mIsCreate || mAlertDate != alertDate) { mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate); } mAlertDate = alertDate; int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); if (mIsCreate || mBgColorId != bgColorId) { mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); } mBgColorId = bgColorId; long createDate = note.has(NoteColumns.CREATED_DATE) ? note.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); if (mIsCreate || mCreatedDate != createDate) { mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate); } mCreatedDate = createDate; int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note.getInt(NoteColumns.HAS_ATTACHMENT) : 0; if (mIsCreate || mHasAttachment != hasAttachment) { mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); } mHasAttachment = hasAttachment; long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis(); if (mIsCreate || mModifiedDate != modifiedDate) { mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); } mModifiedDate = modifiedDate; long parentId = note.has(NoteColumns.PARENT_ID) ? note.getLong(NoteColumns.PARENT_ID) : 0; if (mIsCreate || mParentId != parentId) { mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); } mParentId = parentId; String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : ""; if (mIsCreate || !mSnippet.equals(snippet)) { mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); } mSnippet = snippet; int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE; if (mIsCreate || mType != type) { mDiffNoteValues.put(NoteColumns.TYPE, type); } mType = type; int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) : AppWidgetManager.INVALID_APPWIDGET_ID; if (mIsCreate || mWidgetId != widgetId) { mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); } mWidgetId = widgetId; int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE; if (mIsCreate || mWidgetType != widgetType) { mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); } mWidgetType = widgetType; long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; if (mIsCreate || mOriginParent != originParent) { mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); } mOriginParent = originParent; for (int i = 0; i < dataArray.length(); i++) { JSONObject data = dataArray.getJSONObject(i); SqlData sqlData = null; if (data.has(DataColumns.ID)) { long dataId = data.getLong(DataColumns.ID); for (SqlData temp : mDataList) { if (dataId == temp.getId()) { sqlData = temp; } } } if (sqlData == null) { sqlData = new SqlData(mContext); mDataList.add(sqlData); } sqlData.setContent(data); } } } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); return false; } return true; }
From source file:drusy.ui.panels.SwitchStatePanel.java
public void update(final Updater updater) { final ByteArrayOutputStream output = new ByteArrayOutputStream(); HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(Config.FREEBOX_API_SWITCH_STATUS, output, "Getting Switch status", false); task.addListener(new HttpUtils.DownloadListener() { @Override//from w w w . ja v a2 s . c o m public void onComplete() { String json = output.toString(); JSONObject obj = new JSONObject(json); boolean success = obj.getBoolean("success"); clearUsers(); if (success == true) { JSONArray switchStatusArray = obj.getJSONArray("result"); for (int i = 0; i < switchStatusArray.length(); ++i) { JSONObject switchStatus = switchStatusArray.getJSONObject(i); String status = switchStatus.getString("link"); int id = switchStatus.getInt("id"); if (status.equals("up")) { JSONArray switchMacArray = switchStatus.getJSONArray("mac_list"); JSONObject switchMac = switchMacArray.getJSONObject(i); String hostname = switchMac.getString("hostname"); addUsersForSwitchIdAndHostname(id, hostname); } } } else { String msg = obj.getString("msg"); Log.Debug("Freebox Switch status", msg); } if (updater != null) { updater.updated(); } } }); task.addListener(new HttpUtils.DownloadListener() { @Override public void onError(IOException ex) { Log.Debug("Freebox Switch status", ex.getMessage()); if (updater != null) { updater.updated(); } } }); }
From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderSS.java
private void downloadDatabase(DownloadItem di) throws Exception { String url = di.getAddress(); String jsonString = downloadJSONString(url); JSONObject jsonObject = new JSONObject(jsonString); JSONArray jsonDataArray = jsonObject.getJSONArray("data"); List<Item> itemList = new LinkedList<Item>(); for (int i = 0; i < jsonDataArray.length(); i++) { JSONArray jsonItemArray = jsonDataArray.getJSONArray(i); String question = jsonItemArray.getString(0); String answer = jsonItemArray.getString(1); if (question != null && !question.equals("")) { Item item = new Item(); item.setQuestion(question);/*w w w. j av a 2 s . co m*/ item.setAnswer(answer); item.setId(i + 1); itemList.add(item); } } String dbname = di.getTitle() + ".db"; String dbpath = Environment.getExternalStorageDirectory().getAbsolutePath() + getString(R.string.default_dir); DatabaseHelper.createEmptyDatabase(dbpath, dbname); DatabaseHelper dbHelper = new DatabaseHelper(this, dbpath, dbname); dbHelper.insertListItems(itemList); dbHelper.close(); }
From source file:org.cgiar.ilri.odk.pull.backend.services.FetchFormDataService.java
/** * This method is called whenever the service is called. Note that the service might have * already been running when it was called * * @param intent The intent used to call the service *///from w ww . j a va 2 s. com @Override protected void onHandleIntent(Intent intent) { formName = intent.getStringExtra(KEY_FORM_NAME); if (formName != null) { //fetch data on the form try { String jsonString = DataHandler.sendDataToServer(this, null, DataHandler.URI_FETCH_FORM_DATA + URLEncoder.encode(formName, "UTF-8")); if (jsonString != null) { try { JSONObject jsonObject = new JSONObject(jsonString); JSONObject fileData = jsonObject.getJSONObject("files"); Iterator<String> keys = fileData.keys(); String fetchedFilesString = ""; while (keys.hasNext()) { String currFileName = keys.next(); Log.d(TAG, "Processing " + currFileName); JSONArray currFileData = fileData.getJSONArray(currFileName); if (currFileName.equals(Form.DEFAULT_CSV_FILE_NAME)) { Log.d(TAG, "Treating " + currFileName + " like a itemset file"); Log.d(TAG, currFileName + " data = " + currFileData.toString()); String csv = getCSVString(currFileData); if (csv != null) { saveCSVInFile(currFileName + Form.SUFFIX_CSV, csv); fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName + Form.SUFFIX_CSV; } else { Log.w(TAG, Form.DEFAULT_CSV_FILE_NAME + " from the server is null. Unable to save this on the device"); Toast.makeText(FetchFormDataService.this, getResources().getText(R.string.unable_fetch_data_for) + " " + currFileName, Toast.LENGTH_LONG).show(); } } else { Log.d(TAG, "Treating " + currFileName + " like an external data file"); boolean dataDumped = saveDataInDb(currFileName, currFileData); String csv = getCSVString(currFileData); if (csv != null) { if (dataDumped) { saveCSVInFile(currFileName + Form.SUFFIX_CSV + Form.SUFFIX_IMPORTED, csv); fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName + Form.SUFFIX_DB; fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName + Form.SUFFIX_CSV + Form.SUFFIX_IMPORTED; } else { saveCSVInFile(currFileName + Form.SUFFIX_CSV, csv); fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName + Form.SUFFIX_CSV; } } else { Log.w(TAG, currFileName + " from the server is null. Unable to save this on the device"); Toast.makeText(FetchFormDataService.this, getResources().getText(R.string.unable_fetch_data_for) + " " + currFileName, Toast.LENGTH_LONG).show(); } } } DataHandler.updateFormLastUpdateTime(FetchFormDataService.this, formName); if (fetchedFilesString.length() > 0) {//only show the notification if at least one file updated updateNotification(formName, getString(R.string.fetched_data), getString(R.string.the_following_files_were_added) + fetchedFilesString); } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e(TAG, "Data from server null. Something happened while trying to fetch csv for " + formName); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { Log.w(TAG, "Form name from intent bundle was null, doing nothing"); } }