List of usage examples for org.json JSONArray JSONArray
public JSONArray(Object array) throws JSONException
From source file:com.dzt.uberclone.HomeFragment.java
private void showUberMarkers(String json) { try {//from ww w. j av a2 s . c om markers.clear(); shortestTime = 0; JSONArray jsonArray = new JSONArray(json); nearbyUbers = jsonArray.length(); ubercount = 0; if (nearbyUbers == 0) { displayNoUbersMessage(); } for (int i = 0; i < nearbyUbers; i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); double lat = jsonObject.getDouble("pos_lat"); double lon = jsonObject.getDouble("pos_long"); addUberMarker(lat, lon); getShortestTime(lat, lon); } } catch (JSONException e) { e.printStackTrace(); } }
From source file:org.matrix.console.store.LoginStorage.java
/** * Return a list of HomeserverConnectionConfig. * @return a list of HomeserverConnectionConfig. *//*from w w w. jav a 2 s .c om*/ public ArrayList<HomeserverConnectionConfig> getCredentialsList() { SharedPreferences prefs = mContext.getSharedPreferences(PREFS_LOGIN, Context.MODE_PRIVATE); String connectionConfigsString = prefs.getString(PREFS_KEY_CONNECTION_CONFIGS, null); Log.d(LOG_TAG, "Got connection json: " + connectionConfigsString); if (connectionConfigsString == null) { return new ArrayList<HomeserverConnectionConfig>(); } try { JSONArray connectionConfigsStrings = new JSONArray(connectionConfigsString); ArrayList<HomeserverConnectionConfig> configList = new ArrayList<HomeserverConnectionConfig>( connectionConfigsStrings.length()); for (int i = 0; i < connectionConfigsStrings.length(); i++) { configList.add(HomeserverConnectionConfig.fromJson(connectionConfigsStrings.getJSONObject(i))); } return configList; } catch (JSONException e) { Log.e(LOG_TAG, "Failed to deserialize accounts " + e.getMessage(), e); throw new RuntimeException("Failed to deserialize accounts"); } }
From source file:org.matrix.console.store.LoginStorage.java
/** * Add a credentials to the credentials list * @param config the HomeserverConnectionConfig to add. *//* w ww . j a v a 2s . co m*/ public void addCredentials(HomeserverConnectionConfig config) { if (null != config && config.getCredentials() != null) { SharedPreferences prefs = mContext.getSharedPreferences(PREFS_LOGIN, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); ArrayList<HomeserverConnectionConfig> configs = getCredentialsList(); configs.add(config); ArrayList<JSONObject> serialized = new ArrayList<JSONObject>(configs.size()); try { for (HomeserverConnectionConfig c : configs) { serialized.add(c.toJson()); } } catch (JSONException e) { throw new RuntimeException("Failed to serialize connection config"); } String ser = new JSONArray(serialized).toString(); Log.d(LOG_TAG, "Storing " + serialized.size() + " credentials"); editor.putString(PREFS_KEY_CONNECTION_CONFIGS, ser); editor.commit(); } }
From source file:org.matrix.console.store.LoginStorage.java
/** * Remove the credentials from credentials list * @param config the credentials to remove *//* ww w. j a v a2 s.c o m*/ public void removeCredentials(HomeserverConnectionConfig config) { if (null != config && config.getCredentials() != null) { Log.d(LOG_TAG, "Removing account: " + config.getCredentials().userId); SharedPreferences prefs = mContext.getSharedPreferences(PREFS_LOGIN, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); ArrayList<HomeserverConnectionConfig> configs = getCredentialsList(); ArrayList<JSONObject> serialized = new ArrayList<JSONObject>(configs.size()); boolean found = false; try { for (HomeserverConnectionConfig c : configs) { if (c.getCredentials().userId.equals(config.getCredentials().userId)) { found = true; } else { serialized.add(c.toJson()); } } } catch (JSONException e) { throw new RuntimeException("Failed to serialize connection config"); } if (!found) return; String ser = new JSONArray(serialized).toString(); Log.d(LOG_TAG, "Storing " + serialized.size() + " credentials"); editor.putString(PREFS_KEY_CONNECTION_CONFIGS, ser); editor.commit(); } }
From source file:org.matrix.console.store.LoginStorage.java
/** * Replace the credential from credentials list, based on credentials.userId. * If it does not match an existing credential it does *not* insert the new credentials. * @param config the credentials to insert *//*from w w w . j av a2 s. co m*/ public void replaceCredentials(HomeserverConnectionConfig config) { if (null != config && config.getCredentials() != null) { SharedPreferences prefs = mContext.getSharedPreferences(PREFS_LOGIN, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); ArrayList<HomeserverConnectionConfig> configs = getCredentialsList(); ArrayList<JSONObject> serialized = new ArrayList<JSONObject>(configs.size()); boolean found = false; try { for (HomeserverConnectionConfig c : configs) { if (c.getCredentials().userId.equals(config.getCredentials().userId)) { serialized.add(config.toJson()); found = true; } else { serialized.add(c.toJson()); } } } catch (JSONException e) { throw new RuntimeException("Failed to serialize connection config"); } if (!found) return; String ser = new JSONArray(serialized).toString(); Log.d(LOG_TAG, "Storing " + serialized.size() + " credentials"); editor.putString(PREFS_KEY_CONNECTION_CONFIGS, ser); editor.commit(); } }
From source file:game.Clue.JSONTokener.java
/** * Get the next value. The value can be a Boolean, Double, Integer, * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. * @throws JSONException If syntax error. * * @return An object./*from w w w. j a v a 2 s . co m*/ */ public Object nextValue() throws JSONException { char c = this.nextClean(); String string; switch (c) { case '"': case '\'': return this.nextString(c); case '{': this.back(); return new JSONObject(this); case '[': this.back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuilder sb = new StringBuilder(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = this.next(); } this.back(); string = sb.toString().trim(); if ("".equals(string)) { throw this.syntaxError("Missing value"); } return JSONObject.stringToValue(string); }
From source file:org.indigo.cdmi.backend.radosgw.JsonResponseTranlator.java
/** * Making use of String in JSON format, creates list of BackedCapability objects * related to each QoS profile described in passed JSON. * /* w w w. j av a2 s.c o m*/ * @see GatewayResponseTranslator#getBackendCapabilitiesList(String) */ @Override public List<BackendCapability> getBackendCapabilitiesList(String gatewayResponse) { List<BackendCapability> backendCapabilities = new ArrayList<>(); /* * check input parameters sanity conditions */ if (gatewayResponse == null) { log.error("Argument of name input cannot be null"); throw new IllegalArgumentException("input argument cannot be null"); } /* * convert response from string to JSONArray representation and from * now on treat this object as data model for further processing */ JSONArray backendProfilesArray = new JSONArray(gatewayResponse); log.debug("JSONArray:", backendProfilesArray); /* * iterate over all profiles described by backendProfilesArray, * and for each profile create related BackedndCapability object */ for (int i = 0; i < backendProfilesArray.length(); i++) { JSONObject profileAsJsonObj = backendProfilesArray.getJSONObject(i); log.debug("JSONObject: {}", profileAsJsonObj); BackendCapability backendCapability = createBackedCapability(profileAsJsonObj); log.debug("Created BackendCapability: {}", backendCapability); backendCapabilities.add(backendCapability); } // for() return backendCapabilities; }
From source file:org.obiba.magma.Coordinate.java
public static Coordinate getCoordinateFrom(String string) { // GeoJSON coordinate if (string.trim().startsWith("[")) { JSONArray array = null;//from w w w . j ava 2 s . co m try { array = new JSONArray(string); return getCoordinateFrom(array); } catch (JSONException e) { throw new MagmaRuntimeException("Not a valid GeoJSON coordinate", e); } } // JSON coordinate if (string.trim().startsWith("{")) { JSONObject object = null; try { object = new JSONObject(string); return getCoordinateFrom(object); } catch (JSONException e) { throw new MagmaRuntimeException("Not a valid JSON coordinate", e); } } // Google coordinate lat,long else { String stringToParse = "[" + string.trim() + "]"; JSONArray array = null; try { array = new JSONArray(stringToParse); return new Coordinate(array.getDouble(1), array.getDouble(0)); } catch (JSONException e) { throw new MagmaRuntimeException("Not a valid coordinate", e); } } }
From source file:org.skt.runtime.api.PluginManager.java
/** * Receives a request for execution and fulfills it by finding the appropriate * Java class and calling it's execute method. * /* w w w .j ava2 s . c o m*/ * PluginManager.exec can be used either synchronously or async. In either case, a JSON encoded * string is returned that will indicate if any errors have occurred when trying to find * or execute the class denoted by the clazz argument. * * @param service String containing the service to run * @param action String containt the action that the class is supposed to perform. This is * passed to the plugin execute method and it is up to the plugin developer * how to deal with it. * @param callbackId String containing the id of the callback that is execute in JavaScript if * this is an async plugin call. * @param args An Array literal string containing any arguments needed in the * plugin execute method. * @param async Boolean indicating whether the calling JavaScript code is expecting an * immediate return value. If true, either Srt.callbackSuccess(...) or * Srt.callbackError(...) is called once the plugin code has executed. * * @return JSON encoded string with a response message and status. */ @SuppressWarnings("unchecked") public String exec(final String service, final String action, final String callbackId, final String jsonArgs, final boolean async) { PluginResult cr = null; boolean runAsync = async; try { final JSONArray args = new JSONArray(jsonArgs); final IPlugin plugin = this.getPlugin(service); final RuntimeInterface ctx = this.ctx; if (plugin != null) { runAsync = async && !plugin.isSynch(action); if (runAsync) { // Run this on a different thread so that this one can return back to JS Thread thread = new Thread(new Runnable() { public void run() { try { // Call execute on the plugin so that it can do it's thing PluginResult cr = plugin.execute(action, args, callbackId); int status = cr.getStatus(); // If no result to be sent and keeping callback, then no need to sent back to JavaScript if ((status == PluginResult.Status.NO_RESULT.ordinal()) && cr.getKeepCallback()) { } // Check the success (OK, NO_RESULT & !KEEP_CALLBACK) else if ((status == PluginResult.Status.OK.ordinal()) || (status == PluginResult.Status.NO_RESULT.ordinal())) { ctx.sendJavascript(cr.toSuccessCallbackString(callbackId)); } // If error else { ctx.sendJavascript(cr.toErrorCallbackString(callbackId)); } } catch (Exception e) { PluginResult cr = new PluginResult(PluginResult.Status.ERROR, e.getMessage()); ctx.sendJavascript(cr.toErrorCallbackString(callbackId)); } } }); thread.start(); return ""; } else { // Call execute on the plugin so that it can do it's thing cr = plugin.execute(action, args, callbackId); // If no result to be sent and keeping callback, then no need to sent back to JavaScript if ((cr.getStatus() == PluginResult.Status.NO_RESULT.ordinal()) && cr.getKeepCallback()) { return ""; } } } } catch (JSONException e) { System.out.println("ERROR: " + e.toString()); cr = new PluginResult(PluginResult.Status.JSON_EXCEPTION); } // if async we have already returned at this point unless there was an error... if (runAsync) { if (cr == null) { cr = new PluginResult(PluginResult.Status.CLASS_NOT_FOUND_EXCEPTION); } ctx.sendJavascript(cr.toErrorCallbackString(callbackId)); } return (cr != null ? cr.getJSONString() : "{ status: 0, message: 'all good' }"); }
From source file:me.malladi.dashcricket.Util.java
/** * Fetch the current live scores./*w w w.jav a 2s . com*/ * * @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; }