List of usage examples for org.json JSONArray toString
public String toString()
From source file:com.hanuor.pearl.toolbox.JsonArrayRequest.java
/** * Creates a new request.//from ww w . j a v a2s . c om * @param method the HTTP method to use * @param url URL to fetch the JSON from * @param jsonRequest A {@link JSONArray} to post with the request. Null is allowed and * indicates no parameters will be posted along with request. * @param listener Listener to receive the JSON response * @param errorListener Error listener, or null to ignore errors. */ public JsonArrayRequest(int method, String url, JSONArray jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) { super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener); }
From source file:fr.simon.marquis.secretcodes.util.Utils.java
public static void saveSecretCodes(Context ctx, ArrayList<SecretCode> secretCodes) { Editor ed = PreferenceManager.getDefaultSharedPreferences(ctx).edit(); JSONArray array = new JSONArray(); for (SecretCode code : secretCodes) { array.put(code.toJSON());//from w w w . j a v a 2 s . c o m } ed.putString(KEY_SECRET_CODES, array.toString()); ed.commit(); }
From source file:sandeep.kb.android.remote.android.AndroidWebDriver.java
private List<Object> convertJsonArrayToList(final JSONArray json) { List<Object> toReturn = Lists.newArrayList(); for (int i = 0; i < json.length(); i++) { try {//from www . j a v a2 s. c o m toReturn.add(convertJsonToJavaObject(json.get(i))); } catch (JSONException e) { throw new RuntimeException("Failed to parse JSON: " + json.toString(), e); } } return toReturn; }
From source file:com.wso2.mobile.mdm.api.DeviceInfo.java
/** *Returns the network operator name//from w ww .j av a 2 s .co m */ public JSONArray getNetworkOperatorName() { JSONArray jsonArray = null; final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (CommonUtilities.DEBUG_MODE_ENABLED) { Log.e("Network OP", tm.getSimOperatorName()); } if (tm.getSimOperatorName() != null && tm.getSimOperatorName() != "") { networkOperatorName = tm.getSimOperatorName(); } else { networkOperatorName = "No Sim"; } SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE); try { jsonArray = new JSONArray(mainPref.getString("operators", "[]")); boolean simstatus = false; if (jsonArray.length() > 0) { for (int i = 0; i < jsonArray.length(); i++) { if ((jsonArray.getString(i) != null) && jsonArray.getString(i).trim().equals(tm.getSimOperatorName())) { simstatus = true; } } if (!simstatus) { jsonArray.put(tm.getSimOperatorName()); } } else { jsonArray.put(tm.getSimOperatorName()); } } catch (Exception e) { e.printStackTrace(); } Editor editor = mainPref.edit(); editor.putString("operators", jsonArray.toString()); editor.commit(); return jsonArray; }
From source file:org.corpus_tools.salt.util.tests.VisJsVisualizerTest.java
@Test public void testWriterOutput() throws SaltParameterException, SaltResourceException, SaltException, IOException, XMLStreamException { SDocument doc = SaltFactory.createSDocument(); SampleGenerator.createMorphologyAnnotations(doc); // SDocument doc = visInput.getDocument(); VisJsVisualizer VisJsVisualizer = new VisJsVisualizer(doc); OutputStream osNodes = new ByteArrayOutputStream(); OutputStream osEdges = new ByteArrayOutputStream(); VisJsVisualizer.setNodeWriter(osNodes); VisJsVisualizer.setEdgeWriter(osEdges); VisJsVisualizer.buildJSON();/* w w w . ja v a2 s .com*/ String strNodes = osNodes.toString(); String strEdges = osEdges.toString(); System.out.println(strNodes); System.out.println(strEdges); JSONArray jsonNodes = new JSONArray(strNodes); JSONArray jsonEdges = new JSONArray(strEdges); System.out.println(jsonNodes.toString()); System.out.println(jsonEdges.toString()); }
From source file:com.google.android.gms.location.sample.geofencing.MainActivity.java
private void storeInDb(LatLng latLng) { String towerIds = Constants.NOT_AVAILABLE; if (mNetworkDetailModelList != null && !mNetworkDetailModelList.isEmpty()) { JSONArray array = new JSONArray(); int size = mNetworkDetailModelList.size(); for (int i = 0; i < size; i++) { JSONObject object = new JSONObject(); NetworkDetailModel model = mNetworkDetailModelList.get(i); try { object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.LAC, model.getLac()); object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.TOWER_IDS, model.getCellID()); object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.MNC, model.getMnc()); object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.MCC, model.getMcc()); object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.LAT, latLng.latitude); object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.LNG, latLng.longitude); object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.OPERATOR_NAME, model.getOperatorName()); object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.RSSI, model.getRssid()); array.put(object);/*from w ww . j av a 2s .co m*/ } catch (JSONException ex) { Log.i("Exception", "exception" + ex); } towerIds = array.toString(); } long i = dataSource.insertGeofenceDetails(place, Double.toString(latLng.latitude), Double.toString(latLng.longitude), towerIds, GeoFenceApp.getLocationUtilityInstance().getLocation()); Log.i("tag", "i:" + i); } }
From source file:ssc.SenseSmartCity.java
/** * Request snow pressure readings. This is a compromise greatly simplify the * design of this library but of course limit readings to snow pressure only. * Should of course be able to handle all type of sensors. * /*from w ww . j a v a 2 s .c om*/ * Need a list of sensors, at least one. None throws an exception. Desired * fields is given as a list of queries, this can be empty but only a limit * number of fields is then returned. A time period might be given, none is * needed. All valid periods is found in SSCResources. * * @param sensors List of sensors * @param querys List of fields * @param period Time period * * @return A map with sensor as keys and list of readings as value */ public Map<Sensor, List<SnowPressure>> requestSnowPressure(List<Sensor> sensors, List<String> querys, String period) { nullWatch(sensors); Map<String, String> args = new HashMap<String, String>(); // Filter requested sensors, for now we only accept SnowPressure List<Sensor> sensors_sp = getSensorType(sensors, "SnowPressure"); emptyWatch(sensors_sp); JSONArray sensors_json = new JSONArray(getSensorSerials(sensors_sp)); args.put(SSCResources.Query.SENSORS, sensors_json.toString()); // Fields, none provided means all available. if (notNull(querys) && !querys.isEmpty()) { JSONArray fields_json = new JSONArray(querys); args.put(SSCResources.Query.FIELDS, fields_json.toString()); } // Time period, just ignore it if null. if (notNull(period) && period.trim() != "") { args.put(SSCResources.Query.PERIOD, validatePeriod(period)); } // Undocumented option but needed, else we get XML in return. args.put(SSCResources.Query.FORMAT, "json"); String data = ssc_client.getData(SSCResources.Url.HTTPS_SSC + SSCResources.Url.GET_SNOWPRESURE, args); return parseSnowPressureData(sensors_sp, responseObject(data)); }
From source file:com.rapid.actions.Webservice.java
@Override public JSONObject doAction(RapidRequest rapidRequest, JSONObject jsonAction) throws Exception { _logger.trace("Webservice action : " + jsonAction); // get the application Application application = rapidRequest.getApplication(); // get the page Page page = rapidRequest.getPage();/*from w w w . j a va 2 s . co m*/ // get the webservice action call sequence int sequence = jsonAction.optInt("sequence", 1); // placeholder for the object we're about to return JSONObject jsonData = null; // only proceed if there is a request and application and page if (_request != null && application != null && page != null) { // get any json inputs JSONArray jsonInputs = jsonAction.optJSONArray("inputs"); // placeholder for the action cache ActionCache actionCache = rapidRequest.getRapidServlet().getActionCache(); // if an action cache was found if (actionCache != null) { // log that we found action cache _logger.debug("Webservice action cache found"); // attempt to fetch data from the cache jsonData = actionCache.get(application.getId(), getId(), jsonInputs.toString()); } // if there is either no cache or we got no data if (jsonData == null) { // get the body into a string String body = _request.getBody().trim(); // remove prolog if present if (body.indexOf("\"?>") > 0) body = body.substring(body.indexOf("\"?>") + 3).trim(); // check number of parameters int pCount = Strings.occurrences(body, "?"); // throw error if incorrect if (pCount != jsonInputs.length()) throw new Exception("Request has " + pCount + " parameter" + (pCount == 1 ? "" : "s") + ", " + jsonInputs.length() + " provided"); // retain the current position int pos = body.indexOf("?"); // keep track of the index of the ? int index = 0; // if there are any question marks if (pos > 0 && jsonInputs.length() > index) { // loop, but check condition at the end do { // get the input JSONObject input = jsonInputs.getJSONObject(index); // url escape the value String value = XML.escape(input.optString("value")); // replace the ? with the input value body = body.substring(0, pos) + value + body.substring(pos + 1); // look for the next question mark pos = body.indexOf("?", pos + 1); // inc the index for the next round index++; // stop looping if no more ? } while (pos > 0); } // retrieve the action String action = _request.getAction(); // create a placeholder for the request url URL url = null; // get the request url String requestURL = _request.getUrl(); // if we got one if (requestURL != null) { // if the given request url starts with http use it as is, otherwise use the soa servlet if (_request.getUrl().startsWith("http")) { // trim it requestURL = requestURL.trim(); // insert any parameters requestURL = application .insertParameters(rapidRequest.getRapidServlet().getServletContext(), requestURL); // use the url url = new URL(requestURL); } else { // get our request HttpServletRequest httpRequest = rapidRequest.getRequest(); // make a url for the soa servlet url = new URL(httpRequest.getScheme(), httpRequest.getServerName(), httpRequest.getServerPort(), httpRequest.getContextPath() + "/soa"); // check whether we have any id / version seperators String[] actionParts = action.split("/"); // add this app and version if none if (actionParts.length < 2) action = application.getId() + "/" + application.getVersion() + "/" + action; } // establish the connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // if we are requesting from ourself if (url.getPath().startsWith(rapidRequest.getRequest().getContextPath())) { // get our session id String sessionId = rapidRequest.getRequest().getSession().getId(); // add it to the call for internal authentication connection.setRequestProperty("Cookie", "JSESSIONID=" + sessionId); } // set the content type and action header accordingly if ("SOAP".equals(_request.getType())) { connection.setRequestProperty("Content-Type", "text/xml"); connection.setRequestProperty("SOAPAction", action); } else if ("JSON".equals(_request.getType())) { connection.setRequestProperty("Content-Type", "application/json"); if (action.length() > 0) connection.setRequestProperty("Action", action); } else if ("XML".equals(_request.getType())) { connection.setRequestProperty("Content-Type", "text/xml"); if (action.length() > 0) connection.setRequestProperty("Action", action); } // if a body has been specified if (body.length() > 0) { // Triggers POST. connection.setDoOutput(true); // get the output stream from the connection into which we write the request OutputStream output = connection.getOutputStream(); // write the processed body string into the request output stream output.write(body.getBytes("UTF8")); } // check the response code int responseCode = connection.getResponseCode(); // read input stream if all ok, otherwise something meaningful should be in error stream if (responseCode == 200) { // get the input stream InputStream response = connection.getInputStream(); // prepare an soaData object SOAData soaData = null; // read the response accordingly if ("JSON".equals(_request.getType())) { SOAJSONReader jsonReader = new SOAJSONReader(); String jsonResponse = Strings.getString(response); soaData = jsonReader.read(jsonResponse); } else { SOAXMLReader xmlReader = new SOAXMLReader(_request.getRoot()); soaData = xmlReader.read(response); } SOADataWriter jsonWriter = new SOARapidWriter(soaData); String jsonString = jsonWriter.write(); jsonData = new JSONObject(jsonString); if (actionCache != null) actionCache.put(application.getId(), getId(), jsonInputs.toString(), jsonData); response.close(); } else { InputStream response = connection.getErrorStream(); String errorMessage = null; if ("SOAP".equals(_request.getType())) { String responseXML = Strings.getString(response); errorMessage = XML.getElementValue(responseXML, "faultcode"); } if (errorMessage == null) { BufferedReader rd = new BufferedReader(new InputStreamReader(response)); errorMessage = rd.readLine(); rd.close(); } // log the error _logger.error(errorMessage); // only if there is no application cache show the error, otherwise it sends an empty response if (actionCache == null) { throw new JSONException( " response code " + responseCode + " from server : " + errorMessage); } else { _logger.debug("Error not shown to user due to cache : " + errorMessage); } } connection.disconnect(); } // request url != null } // jsonData == null } // got app and page // if the jsonData is still null make an empty one if (jsonData == null) jsonData = new JSONObject(); // add the sequence jsonData.put("sequence", sequence); // return the object return jsonData; }
From source file:de.kp.ames.web.core.search.SearcherImpl.java
public String facet() throws Exception { /*/*from www. j a va 2s .c o m*/ * Create query */ SolrQuery query = new SolrQuery(); query.setRows(0); /* * A single facet field is supported */ query.addFacetField(JsonConstants.J_FACET); query.setQuery("*"); /* * Retrieve facets from Apache Solr */ QueryResponse response = solrProxy.executeQuery(query); FacetField facet = response.getFacetField(JsonConstants.J_FACET); /* * Evaluate response */ if (facet == null) return new JSONArray().toString(); /* * Sort search result */ StringCollector collector = new StringCollector(); List<Count> values = facet.getValues(); if (values == null) return new JSONArray().toString(); for (int i = 0; i < values.size(); i++) { Count count = values.get(i); String name = facet.getName(); JSONObject jCount = new JSONObject(); jCount.put(JsonConstants.J_COUNT, count.getCount()); jCount.put(JsonConstants.J_FIELD, facet.getName()); jCount.put(JsonConstants.J_VALUE, count.getName()); collector.put(name, jCount); } JSONArray jArray = new JSONArray(collector.values()); return jArray.toString(); }
From source file:de.kp.ames.web.core.search.SearcherImpl.java
public String suggest(String request, String start, String limit) throws Exception { /*//from w w w.j a v a 2 s .c o m * Retrieve terms */ SolrQuery query = new SolrQuery(); query.setParam(CommonParams.QT, "/terms"); query.setParam(TermsParams.TERMS, true); query.setParam(TermsParams.TERMS_LIMIT, SearchConstants.TERMS_LIMIT); query.setParam(TermsParams.TERMS_FIELD, SearchConstants.TERMS_FIELD); query.setParam(TermsParams.TERMS_PREFIX_STR, request); QueryResponse response = solrProxy.executeQuery(query); NamedList<Object> terms = getTerms(response); JSONArray jTerms = getTermValues(SearchConstants.TERMS_FIELD, terms); /* * Render result for DataSource */ return jTerms.toString(); }