List of usage examples for org.json JSONArray opt
public Object opt(int index)
From source file:me.malladi.dashcricket.Util.java
/** * Fetch the current live scores./*from ww w. j av a 2 s . c o m*/ * * @return An array of the current live scores. */ public static LiveScore[] getLiveScores() { try { URL url = new URL(LIVE_SCORES_URL); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setUseCaches(false); BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder json = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { json.append(line); } JSONArray jsonArray = new JSONArray(json.toString()); LiveScore[] liveScores = new LiveScore[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); ++i) { JSONObject liveScoreJson = (JSONObject) jsonArray.opt(i); liveScores[i] = new LiveScore(liveScoreJson); } return liveScores; } catch (Exception e) { Log.e(TAG, "exception while fetching live scores", e); } return null; }
From source file:com.trk.aboutme.facebook.Request.java
private static void processGraphObjectProperty(String key, Object value, KeyValueSerializer serializer, boolean passByValue) throws IOException { Class<?> valueClass = value.getClass(); if (GraphObject.class.isAssignableFrom(valueClass)) { value = ((GraphObject) value).getInnerJSONObject(); valueClass = value.getClass();/*w w w .j a va 2 s .com*/ } else if (GraphObjectList.class.isAssignableFrom(valueClass)) { value = ((GraphObjectList<?>) value).getInnerJSONArray(); valueClass = value.getClass(); } if (JSONObject.class.isAssignableFrom(valueClass)) { JSONObject jsonObject = (JSONObject) value; if (passByValue) { // We need to pass all properties of this object in key[propertyName] format. @SuppressWarnings("unchecked") Iterator<String> keys = jsonObject.keys(); while (keys.hasNext()) { String propertyName = keys.next(); String subKey = String.format("%s[%s]", key, propertyName); processGraphObjectProperty(subKey, jsonObject.opt(propertyName), serializer, passByValue); } } else { // Normal case is passing objects by reference, so just pass the ID or URL, if any, as the value // for "key" if (jsonObject.has("id")) { processGraphObjectProperty(key, jsonObject.optString("id"), serializer, passByValue); } else if (jsonObject.has("url")) { processGraphObjectProperty(key, jsonObject.optString("url"), serializer, passByValue); } } } else if (JSONArray.class.isAssignableFrom(valueClass)) { JSONArray jsonArray = (JSONArray) value; int length = jsonArray.length(); for (int i = 0; i < length; ++i) { String subKey = String.format("%s[%d]", key, i); processGraphObjectProperty(subKey, jsonArray.opt(i), serializer, passByValue); } } else if (String.class.isAssignableFrom(valueClass) || Number.class.isAssignableFrom(valueClass) || Boolean.class.isAssignableFrom(valueClass)) { serializer.writeString(key, value.toString()); } else if (Date.class.isAssignableFrom(valueClass)) { Date date = (Date) value; // The "Events Timezone" platform migration affects what date/time formats Facebook accepts and returns. // Apps created after 8/1/12 (or apps that have explicitly enabled the migration) should send/receive // dates in ISO-8601 format. Pre-migration apps can send as Unix timestamps. Since the future is ISO-8601, // that is what we support here. Apps that need pre-migration behavior can explicitly send these as // integer timestamps rather than Dates. final SimpleDateFormat iso8601DateFormat = new SimpleDateFormat(ISO_8601_FORMAT_STRING, Locale.US); serializer.writeString(key, iso8601DateFormat.format(date)); } }
From source file:com.ca.mas.cordova.storage.MASStoragePlugin.java
private void saveToLocal(final JSONArray args, final CallbackContext callbackContext) { try {/*from ww w .j a va 2s .c o m*/ MASStorage storage = new MASSecureLocalStorage(); String key = args.optString(1); Object data = args.opt(2); int segment_0 = args.getInt(3); int segment = fetchSegmentLocal(segment_0); storage.save(key, data, segment, new MASCallback<Void>() { @Override public void onSuccess(Void result) { success(callbackContext, true, false); } @Override public void onError(Throwable e) { callbackContext.error(getError(e)); } }); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); callbackContext.error(getError(e)); } }
From source file:com.ca.mas.cordova.storage.MASStoragePlugin.java
private void saveToCloud(final JSONArray args, final CallbackContext callbackContext) { try {// www. ja v a2s. co m MASStorage storage = new MASSecureStorage(); String key = args.optString(1); Object data = args.opt(2); int segment_0 = args.getInt(3); int segment = fetchSegmentCloud(segment_0); storage.save(key, data, segment, new MASCallback<Void>() { @Override public void onSuccess(Void result) { success(callbackContext, true, false); } @Override public void onError(Throwable e) { Log.e(TAG, e.getMessage()); callbackContext.error(getError(e)); } }); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); callbackContext.error(getError(e)); } }
From source file:fr.arnaudguyon.xmltojsonlib.XmlToJson.java
private void formatArray(JSONArray array, StringBuilder builder, String indent) { builder.append("[\n"); for (int i = 0; i < array.length(); ++i) { Object element = array.opt(i); if (element instanceof JSONObject) { JSONObject child = (JSONObject) element; builder.append(indent);/* ww w . j av a 2 s. c o m*/ builder.append(mIndentationPattern); builder.append("{\n"); format(child, builder, indent + mIndentationPattern); builder.append(indent); builder.append(mIndentationPattern); builder.append("}"); } else if (element instanceof JSONArray) { JSONArray child = (JSONArray) element; formatArray(child, builder, indent + mIndentationPattern); } else { formatValue(element, builder); } if (i < array.length() - 1) { builder.append(","); } builder.append("\n"); } builder.append(indent); builder.append("]"); }
From source file:com.jsonstore.jackson.JsonOrgJSONArraySerializer.java
private void serializeContents(JSONArray value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { int length = value.length(); for (int i = 0; i < length; ++i) { Class<?> cls;//from ww w . jav a 2s. c o m Object obj = value.opt(i); if ((obj == null) || (obj == JSONObject.NULL)) { jgen.writeNull(); continue; } cls = obj.getClass(); if ((cls == JSONObject.class) || JSONObject.class.isAssignableFrom(cls)) { JsonOrgJSONObjectSerializer.instance.serialize((JSONObject) obj, jgen, provider); } else if ((cls == JSONArray.class) || JSONArray.class.isAssignableFrom(cls)) { serialize((JSONArray) obj, jgen, provider); } else if (cls == String.class) { jgen.writeString((String) obj); } else if (cls == Integer.class) { jgen.writeNumber(((Integer) obj).intValue()); } else if (cls == Long.class) { jgen.writeNumber(((Long) obj).longValue()); } else if (cls == Boolean.class) { jgen.writeBoolean(((Boolean) obj).booleanValue()); } else if (cls == Double.class) { jgen.writeNumber(((Double) obj).doubleValue()); } else { provider.defaultSerializeValue(obj, jgen); } } }
From source file:org.marietjedroid.connect.MarietjeClientChannel.java
public void handleMessage(String token, JSONObject data) throws JSONException { System.out.println("processing" + data.toString()); if (data.getString("type").equals("media_part")) { synchronized (tracksRetrieved) { JSONObject ding = data.getJSONObject("part"); @SuppressWarnings("unchecked") Iterator<String> it = ding.keys(); while (it.hasNext()) tempPartialMedia.add(ding.getJSONArray((it.next().toString()))); if (this.partialMediaSize == tempPartialMedia.size()) { this.partialMedia = tempPartialMedia.toArray(new JSONArray[0]); this.tempPartialMedia.clear(); this.partialMediaSize = -1; tracksRetrieved.release(); }//from w ww . ja va 2 s. c om } } else if (data.getString("type").equals("media")) { synchronized (tracksRetrieved) { this.partialMediaSize = data.getInt("count"); if (this.partialMediaSize == tempPartialMedia.size()) { this.partialMedia = tempPartialMedia.toArray(new JSONArray[0]); this.tempPartialMedia.clear(); this.partialMediaSize = 0; tracksRetrieved.release(); } } } else if (data.getString("type").equals("welcome")) return; else if (data.getString("type").equals("playing")) { this.nowPlaying = data.getJSONObject("playing"); playingRetrieved.release(); } else if (data.getString("type").equals("requests")) { this.requests = data.getJSONArray("requests"); this.requestsRetrieved.release(); } else if (data.getString("type").equals("error_login")) { synchronized (loginAttempt) { this.loginError = new MarietjeException(data.getString("message")); this.loginAttempt.release(); } } else if (data.getString("type").equals("login_token")) { synchronized (this.loginToken) { this.loginToken = data.getString("login_token"); this.loginAttempt.release(); } } else if (data.getString("type").equals("logged_in")) { synchronized (loginAttempt) { this.accessKey = data.getString("accessKey"); loginAttempt.release(); } } else if (data.getString("type").equals("error_request")) { this.requestError = data.getString("message"); this.requestsRetrieved.release(); } else if (data.getString("type").equals("query_media_results")) { if (data.getInt("token") != server.queryToken) { return; // wrong result set } synchronized (this.queryResults) { this.queryResults.clear(); JSONArray results = data.getJSONArray("results"); for (int i = 0; results.opt(i) != null; i++) { JSONObject m = results.getJSONObject(i); this.queryResults.add(new MarietjeTrack(m)); } this.queryResultsRetrieved.release(); } } this.setChanged(); this.notifyObservers(data.getString("type")); }
From source file:org.official.json.CDL.java
/** * Produce a comma delimited text row from a JSONArray. Values containing * the comma character will be quoted. Troublesome characters may be * removed./*from w ww .j a va 2 s . c o m*/ * @param ja A JSONArray of strings. * @return A string ending in NEWLINE. */ public static String rowToString(JSONArray ja) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < ja.length(); i += 1) { if (i > 0) { sb.append(','); } Object object = ja.opt(i); if (object != null) { String string = object.toString(); if (string.length() > 0 && (string.indexOf(',') >= 0 || string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 || string.indexOf(0) >= 0 || string.charAt(0) == '"')) { sb.append('"'); int length = string.length(); for (int j = 0; j < length; j += 1) { char c = string.charAt(j); if (c >= ' ' && c != '"') { sb.append(c); } } sb.append('"'); } else { sb.append(string); } } } sb.append('\n'); return sb.toString(); }
From source file:fr.arnaudguyon.xmltojsonlib.JsonToXml.java
private void prepareArray(Node node, String key, JSONArray array) { int count = array.length(); String path = node.getPath() + "/" + key; for (int i = 0; i < count; ++i) { Node subNode = new Node(key, path); Object object = array.opt(i); if (object != null) { if (object instanceof JSONObject) { JSONObject jsonObject = (JSONObject) object; prepareObject(subNode, jsonObject); } else if (object instanceof JSONArray) { JSONArray subArray = (JSONArray) object; prepareArray(subNode, key, subArray); } else { String value = object.toString(); subNode.setName(key);/*w w w . ja v a 2s . co m*/ subNode.setContent(value); } } node.addChild(subNode); } }
From source file:org.jdesktop.http.async.JsonHttpRequest.java
private void stuffIntoArray(JSONArray a, Object[] array) { if (a == null) { return;/*from w w w . java 2 s . c o m*/ } for (int i = 0; i < array.length; i++) { Object value = a.opt(i); if (value instanceof JSONObject) { JSONObject obj = (JSONObject) value; Map<String, Object> map = new HashMap<String, Object>(); stuffIntoMap(obj, map); array[i] = map; } else if (value instanceof JSONArray) { JSONArray ja = (JSONArray) value; Object[] o = new Object[ja.length()]; stuffIntoArray(ja, o); array[i] = o; } else { array[i] = value; } } }