List of usage examples for org.json JSONObject optJSONArray
public JSONArray optJSONArray(String key)
From source file:pubsub.io.processing.Pubsub.java
/** * React to messages...//from ww w. j a va 2 s .co m */ @Override public void onMessage(JSONObject msg) { if (DEBUG) System.out.println(DEBUGTAG + msg.toString()); int callback_id = 0; callback_id = msg.getInt("id"); if (msg.optJSONObject("doc") != null) { JSONObject doc = msg.getJSONObject("doc"); // Get the callback method Method eventMethod = callbacks.get(callback_id); if (eventMethod != null) { try { // Invoke only if the method existed eventMethod.invoke(myParent, doc); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } else if (msg.optJSONArray("doc") != null) { JSONArray doc = msg.getJSONArray("doc"); // Get the callback method Method eventMethod = callbacks.get(callback_id); if (eventMethod != null) { try { // Invoke only if the method existed eventMethod.invoke(myParent, doc); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } else { // Neither... } }
From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java
public String sendJSON(Storage storage, String path, JSONObject data, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { final String WORKFLOW_TRANSITION = "workflowTransition"; final String WORKFLOW_TRANSITION_LOCK = "lock"; JSONObject fields = data.optJSONObject("fields"); JSONArray relations = data.optJSONArray("relations"); if (path != null) { // Update if (fields != null) storage.updateJSON(base + "/" + path, fields, restrictions); } else {//from ww w . ja v a2 s .c om // Create if (fields != null) path = storage.autocreateJSON(base, fields, restrictions); } if (relations != null) setRelations(storage, path, relations); if (record.supportsLocking() && data.has(WORKFLOW_TRANSITION) && WORKFLOW_TRANSITION_LOCK.equalsIgnoreCase(data.getString(WORKFLOW_TRANSITION))) { // If any problem, will throw exception. storage.transitionWorkflowJSON(base + "/" + path, WORKFLOW_TRANSITION_LOCK); } return path; }
From source file:com.google.blockly.model.FieldDropdown.java
/** * Loads a FieldDropdown from JSON. This is usually used for the {@link BlockFactory}'s * prototype instances.// w ww . jav a2 s.c o m * * @param json The JSON representing the object. * @return A new FieldDropdown instance. * @throws BlockLoadingException */ public static FieldDropdown fromJson(JSONObject json) throws BlockLoadingException { String name = json.optString("name"); if (TextUtils.isEmpty(name)) { throw new BlockLoadingException("field_dropdown \"name\" attribute must not be empty."); } JSONArray jsonOptions = json.optJSONArray("options"); ArrayList<Option> optionList = null; if (jsonOptions != null) { int count = jsonOptions == null ? 0 : jsonOptions.length(); optionList = new ArrayList<>(count); for (int i = 0; i < count; i++) { JSONArray option = null; try { option = jsonOptions.getJSONArray(i); } catch (JSONException e) { throw new BlockLoadingException("Error reading dropdown options.", e); } if (option != null && option.length() == 2) { try { String displayName = option.getString(0); String value = option.getString(1); if (TextUtils.isEmpty(value)) { throw new BlockLoadingException("Option values may not be empty"); } optionList.add(new Option(value, displayName)); } catch (JSONException e) { throw new BlockLoadingException("Error reading option values.", e); } } } } return new FieldDropdown(name, new Options(optionList)); }
From source file:com.norman0406.slimgress.API.Interface.RequestResult.java
public static void handleRequest(JSONObject json, RequestResult result) { if (result == null) throw new RuntimeException("invalid result object"); try {/*from w ww . j a va2 s . c o m*/ // handle exception string if available String excString = json.optString("exception"); if (excString.length() > 0) result.handleException(excString); // handle error code if available String error = json.optString("error"); if (error.length() > 0) result.handleError(error); else if (json.has("error")) Log.w("RequestResult", "request contains an unknown error type"); // handle game basket if available JSONObject gameBasket = json.optJSONObject("gameBasket"); if (gameBasket != null) result.handleGameBasket(new GameBasket(gameBasket)); // handle result if available JSONObject resultObj = json.optJSONObject("result"); JSONArray resultArr = json.optJSONArray("result"); String resultStr = json.optString("result"); if (resultObj != null) result.handleResult(resultObj); else if (resultArr != null) result.handleResult(resultArr); else if (resultStr != null) result.handleResult(resultStr); else if (json.has("result")) Log.w("RequestResult", "request contains an unknown result type"); result.finished(); } catch (JSONException e) { e.printStackTrace(); } }
From source file:org.akop.ararat.io.WSJFormatter.java
@Override public void read(Crossword.Builder builder, InputStream inputStream) throws IOException { InputStreamReader reader = new InputStreamReader(inputStream, mEncoding); StringBuilder sb = new StringBuilder(); int nread;// ww w . j av a 2 s . co m char[] buffer = new char[4000]; while ((nread = reader.read(buffer, 0, buffer.length)) > -1) { sb.append(buffer, 0, nread); } JSONObject obj; try { obj = new JSONObject(sb.toString()); } catch (JSONException e) { throw new FormatException("Error parsing JSON object", e); } JSONObject dataObj = obj.optJSONObject("data"); if (dataObj == null) { throw new FormatException("Missing 'data'"); } JSONObject copyObj = dataObj.optJSONObject("copy"); if (copyObj == null) { throw new FormatException("Missing 'data.copy'"); } JSONObject gridObj = copyObj.optJSONObject("gridsize"); if (gridObj == null) { throw new FormatException("Missing 'data.copy.gridsize'"); } builder.setTitle(copyObj.optString("title")); builder.setDescription(copyObj.optString("description")); builder.setCopyright(copyObj.optString("publisher")); builder.setAuthor(copyObj.optString("byline")); String pubString = copyObj.optString("date-publish"); try { builder.setDate(PUBLISH_DATE_FORMAT.parse(pubString).getTime()); } catch (ParseException e) { throw new FormatException("Can't parse '" + pubString + "' as publish date"); } int width = gridObj.optInt("cols"); int height = gridObj.optInt("rows"); builder.setWidth(width); builder.setHeight(height); readClues(builder, copyObj, Grid.parseJSON(dataObj.optJSONArray("grid"), width, height)); }
From source file:org.akop.ararat.io.WSJFormatter.java
private static void readClues(Crossword.Builder builder, JSONObject copyObj, Grid grid) { JSONArray cluesArray = copyObj.optJSONArray("clues"); if (cluesArray == null) { throw new FormatException("Missing 'data.copy.clues[]'"); } else if (cluesArray.length() != 2) { throw new FormatException("Unexpected clues length of '" + cluesArray.length() + "'"); }//from w ww. ja va 2 s .com JSONArray wordsArray = copyObj.optJSONArray("words"); if (wordsArray == null) { throw new FormatException("Missing 'data.copy.words[]'"); } // We'll need this to assign x/y locations to each clue SparseArray<Word> words = new SparseArray<>(); for (int i = 0, n = wordsArray.length(); i < n; i++) { Word word; try { word = Word.parseJSON(wordsArray.optJSONObject(i)); } catch (Exception e) { throw new FormatException("Error parsing 'data.copy.words[" + i + "]'", e); } words.put(word.mId, word); } // Go through the list of clues for (int i = 0, n = cluesArray.length(); i < n; i++) { JSONObject clueObj = cluesArray.optJSONObject(i); if (clueObj == null) { throw new FormatException("'data.copy.clues[" + i + "]' is null"); } JSONArray subcluesArray = clueObj.optJSONArray("clues"); if (subcluesArray == null) { throw new FormatException("Missing 'data.copy.clues[" + i + "].clues'"); } int dir; String clueDir = clueObj.optString("title"); if ("Across".equalsIgnoreCase(clueDir)) { dir = Crossword.Word.DIR_ACROSS; } else if ("Down".equalsIgnoreCase(clueDir)) { dir = Crossword.Word.DIR_DOWN; } else { throw new FormatException("Invalid direction: '" + clueDir + "'"); } for (int j = 0, o = subcluesArray.length(); j < o; j++) { JSONObject subclue = subcluesArray.optJSONObject(j); Word word = words.get(subclue.optInt("word", -1)); if (word == null) { throw new FormatException( "No matching word for clue at 'data.copy.clues[" + i + "].clues[" + j + "].word'"); } Crossword.Word.Builder wb = new Crossword.Word.Builder().setDirection(dir) .setHint(subclue.optString("clue")).setNumber(subclue.optInt("number")) .setStartColumn(word.mCol).setStartRow(word.mRow); if (dir == Crossword.Word.DIR_ACROSS) { for (int k = word.mCol, l = 0; l < word.mLen; k++, l++) { Square square = grid.mSquares[word.mRow][k]; if (square == null) { throw new FormatException( "grid[" + word.mRow + "][" + k + "] is null (it shouldn't be)"); } wb.addCell(square.mChar, 0); } } else { for (int k = word.mRow, l = 0; l < word.mLen; k++, l++) { Square square = grid.mSquares[k][word.mCol]; if (square == null) { throw new FormatException( "grid[" + k + "][" + word.mCol + "] is null (it shouldn't be)"); } wb.addCell(square.mChar, 0); } } builder.addWord(wb.build()); } } }
From source file:com.appsimobile.appsii.module.weather.ImageDownloadHelper.java
public static void getEligiblePhotosFromResponse(@Nullable JSONObject jsonObject, List<PhotoInfo> result, int minDimension) { result.clear();//from w ww . ja va2s .co m if (jsonObject == null) return; JSONObject photos = jsonObject.optJSONObject("photos"); if (photos == null) return; JSONArray photoArr = photos.optJSONArray("photo"); if (photoArr == null) return; int N = photoArr.length(); for (int i = 0; i < N; i++) { JSONObject object = photoArr.optJSONObject(i); if (object == null) continue; String id = object.optString("id"); if (TextUtils.isEmpty(id)) continue; String urlH = urlFromImageObject(object, "url_h", "width_h", "height_h", minDimension - 100); String urlO = urlFromImageObject(object, "url_o", "width_o", "height_o", minDimension - 100); if (urlH != null) { result.add(new PhotoInfo(id, urlH)); } else if (urlO != null) { result.add(new PhotoInfo(id, urlO)); } } }
From source file:com.nascent.android.glass.glasshackto.greenpfinder.model.GreenPSpots.java
/** * Populates the internal places list from places found in a JSON string. This string should * contain a root object with a "landmarks" property that is an array of objects that represent * places. A place has three properties: name, latitude, and longitude. *///from www.j a v a2 s . c om private void populatePlaceList(String jsonString) { try { JSONObject json = new JSONObject(jsonString); JSONArray array = json.optJSONArray("carparks"); if (array != null) { for (int i = 0; i < array.length(); i++) { JSONObject object = array.optJSONObject(i); ParkingLot parkingLot = jsonObjectToParkingLot(object); if (parkingLot != null) { mParkingLots.add(parkingLot); } } } } catch (JSONException e) { Log.e(TAG, "Could not parse landmarks JSON string", e); } }
From source file:org.catnut.fragment.ConversationFragment.java
@Override protected void refresh() { // ???/*from ww w .j a v a 2 s.com*/ if (!isNetworkAvailable()) { Toast.makeText(getActivity(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show(); initFromLocal(); return; } // refresh! final int size = getFetchSize(); (new Thread(new Runnable() { @Override public void run() { // ??????(?-)???Orz... String query = CatnutUtils.buildQuery(new String[] { BaseColumns._ID }, null, Comment.TABLE, null, BaseColumns._ID + " desc", size + ", 1" // limit x, y ); Cursor cursor = getActivity().getContentResolver().query(CatnutProvider.parse(Status.MULTIPLE), null, query, null, null); // the cursor never null? final long since_id; if (cursor.moveToNext()) { since_id = cursor.getLong(0); } else { since_id = 0; } cursor.close(); final CatnutAPI api = CommentsAPI.to_me(since_id, 0, getFetchSize(), 0, 0, 0); // refresh... mHandler.post(new Runnable() { @Override public void run() { mRequestQueue.add(new CatnutRequest(getActivity(), api, new StatusProcessor.Comments2MeProcessor(), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "refresh done..."); mTotal = response.optInt(TOTAL_NUMBER); // ??? JSONArray jsonArray = response.optJSONArray(Comment.MULTIPLE); int newSize = jsonArray.length(); // ... Bundle args = new Bundle(); args.putInt(TAG, newSize); getLoaderManager().restartLoader(0, args, ConversationFragment.this); } }, errorListener)).setTag(TAG); } }); } })).start(); }
From source file:org.catnut.fragment.ConversationFragment.java
private void loadFromCloud(long max_id) { mSwipeRefreshLayout.setRefreshing(true); CatnutAPI api = CommentsAPI.to_me(0, max_id, getFetchSize(), 0, 0, 0); mRequestQueue.add(new CatnutRequest(getActivity(), api, new StatusProcessor.Comments2MeProcessor(), new Response.Listener<JSONObject>() { @Override/* www . j ava 2s .co m*/ public void onResponse(JSONObject response) { Log.d(TAG, "load more from cloud done..."); mTotal = response.optInt(TOTAL_NUMBER); int newSize = response.optJSONArray(Comment.MULTIPLE).length() + mAdapter.getCount(); Bundle args = new Bundle(); args.putInt(TAG, newSize); getLoaderManager().restartLoader(0, args, ConversationFragment.this); } }, errorListener)).setTag(TAG); }