List of usage examples for org.json JSONArray toString
public String toString()
From source file:com.tedx.webservices.WebServices.java
public static JSONArray SendHttpPostArray(String URL, JSONObject jsonObjSend) { try {//from w ww. j av a 2 s. c om DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPostRequest = new HttpPost(URL); StringEntity se; se = new StringEntity(jsonObjSend.toString()); // Set HTTP parameters httpPostRequest.setEntity(se); httpPostRequest.setHeader("Accept", "application/json"); httpPostRequest.setHeader("Content-type", "application/json"); //httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression long t = System.currentTimeMillis(); HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]"); // Get hold of the response entity (-> the data): HttpEntity entity = response.getEntity(); if (entity != null) { // Read the content stream InputStream instream = entity.getContent(); Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { instream = new GZIPInputStream(instream); } // convert content stream to a String String resultString = convertStreamToString(instream); instream.close(); // Transform the String into a JSONObject JSONArray jsonObjRecv = new JSONArray(resultString); // Raw DEBUG output of our received JSON object: Log.i(TAG, "<jsonobject>\n" + jsonObjRecv.toString() + "\n</jsonobject>"); return jsonObjRecv; } } catch (Exception e) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } return null; }
From source file:com.moez.QKSMS.model.MediaModelFactory.java
private static boolean hasBeenPosted(Context context, JSONArray array) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(array.toString().getBytes()); String encryptedString = new String(messageDigest.digest()); return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(encryptedString, false); }
From source file:com.moez.QKSMS.model.MediaModelFactory.java
private static void savePostStatus(Context context, JSONArray array, boolean posted) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(array.toString().getBytes()); String encryptedString = new String(messageDigest.digest()); PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(encryptedString, true); }
From source file:com.trk.aboutme.facebook.InsightsLogger.java
private static String buildJSONForEvent(String eventName, double valueToSum, Bundle parameters) { String result;/* w ww. ja v a 2s .c om*/ try { // Build custom event payload JSONObject eventObject = new JSONObject(); eventObject.put("_eventName", eventName); if (valueToSum != 1.0) { eventObject.put("_valueToSum", valueToSum); } if (parameters != null) { Set<String> keys = parameters.keySet(); for (String key : keys) { Object value = parameters.get(key); if (!(value instanceof String) && !(value instanceof Number)) { notifyDeveloperError( String.format("Parameter '%s' must be a string or a numeric type.", key)); } eventObject.put(key, value); } } JSONArray eventArray = new JSONArray(); eventArray.put(eventObject); result = eventArray.toString(); } catch (JSONException exception) { notifyDeveloperError(exception.toString()); result = null; } return result; }
From source file:com.llbt.meepwn.lincolnblock.library.volley.toolbox.JsonArrayRequest.java
/** * Creates a new request.//from ww w . j a v a 2s. co m * @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<JSONArray> listener, Response.ErrorListener errorListener) { super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener); }
From source file:com.eTilbudsavis.etasdk.network.impl.JsonArrayRequest.java
public JsonArrayRequest(Method method, String url, JSONArray requestBody, Listener<JSONArray> listener) { super(method, url, requestBody == null ? null : requestBody.toString(), listener); init();/*w ww . j a v a 2 s . co m*/ }
From source file:org.sc.probro.servlets.BiothesaurusQueryServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String, String[]> params = decodedParams(request); if (!params.containsKey("search")) { String msg = "No 'search' parameter given"; Log.warn(msg);/*w w w . j a v a 2 s.c om*/ response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return; } String query = params.get("search")[0]; String contentType = decodeResponseType(params, CONTENT_TYPE_JSON); try { if (!SUPPORTED_CONTENT_TYPES.contains(contentType)) { throw new BrokerException(HttpServletResponse.SC_BAD_REQUEST, String.format("Unsupported content type: %s", contentType)); } BiothesaurusSearcher searcher = new BiothesaurusSearcher(biothesaurusIndex, uniprotMappingFile); try { Collection<Document> docs = searcher.search(searcher.createQuery(query)); JSONArray hits = renderDocumentsAsHits(searcher, docs); response.setContentType(contentType); response.setStatus(HttpServletResponse.SC_OK); if (contentType.equals(CONTENT_TYPE_JSON)) { response.getWriter().println(hits.toString()); } else if (contentType.equals(CONTENT_TYPE_HTML)) { PrintWriter pw = response.getWriter(); pw.println("<table>"); pw.println("<tr><th>ID</th><th>Type</th><th>Descriptions</th><th>PRO</th></tr>"); for (int i = 0; i < hits.length(); i++) { JSONObject hit = (JSONObject) hits.get(i); String htmlHit = renderHitAsHTML(hit); pw.println(htmlHit); } pw.println("</table>"); } } catch (JSONException e) { throw new BrokerException(e); } finally { searcher.close(); } } catch (BrokerException e) { handleException(response, e); return; } }
From source file:com.imos.sample.pi.TemperatureSensor.java
public void pythonTemperatureSensor() { try {//from w w w . ja va 2s . co m String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 11 4"; int count = 0; JSONArray array = new JSONArray(); int dayOfMonth = 0; cal.setTime(new Date()); dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); while (true) { Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); StringBuilder output = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { output.append(line); } String result = output.toString(), tempStr; double temp, humid; if (!result.trim().isEmpty()) { tempStr = result.substring(result.indexOf("Humid")); result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1); temp = Double.parseDouble(result); result = tempStr; result = result.substring(result.indexOf("=") + 1, result.indexOf("%")); humid = Double.parseDouble(result); JSONObject data = new JSONObject(); data.put("temp", temp); data.put("humid", humid); data.put("time", new Date().getTime()); array.put(data); } Thread.sleep(60000); count++; if (count == 60) { Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, null, ""); cal.setTime(new Date()); StringBuilder builder = new StringBuilder(); builder.append(cal.get(Calendar.DAY_OF_MONTH)); builder.append("-"); builder.append(cal.get(Calendar.MONTH)); builder.append("-"); builder.append(cal.get(Calendar.YEAR)); builder.append("-"); builder.append(cal.get(Calendar.HOUR_OF_DAY)); builder.append("_"); builder.append(cal.get(Calendar.MINUTE)); try (BufferedWriter writer = new BufferedWriter( new FileWriter(builder.toString() + "_data.json"))) { writer.append(array.toString()); } catch (IOException ex) { } System.out.println(builder.toString()); count = 0; array = new JSONArray(); if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) { builder = new StringBuilder(); builder.append(cal.get(Calendar.DAY_OF_MONTH)); builder.append("-"); builder.append(cal.get(Calendar.MONTH)); builder.append("-"); builder.append(cal.get(Calendar.YEAR)); String dirName = builder.toString(); File newDir = new File("src/main/resources/" + dirName); newDir.mkdir(); File files = new File("src/main/resources/"); for (File file : files.listFiles()) { if (file.getName().endsWith(".json")) { file.renameTo(new File("src/main/resources/" + dirName + file.getName())); file.delete(); } } dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); } } } } catch (IOException | InterruptedException ex) { Logger.getLogger(TemperatureSensor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.air.RecipeFinder.java
public static JSONArray trigger(JSONObject object) throws UnirestException, IOException, JSONException, ParseException { //JSONObject object = getJsonObject(); System.out.println("recieved object : " + object.toString()); Calendar calendar = Calendar.getInstance(); String timestamp = calendar.getTime().toString().replaceAll("\\s+:", "").replaceAll(":", ""); String cuisine = object.getJSONObject("query").getString("cuisine").replaceAll(" ", "+").replaceAll(",", "%2C"); String excludeIngredients = object.getJSONObject("query").getString("excludeIngredients") .replaceAll(" ", "+").replaceAll(",", "%2C"); String includeIngredients = object.getJSONObject("query").getString("includeIngredients") .replaceAll(" ", "+").replaceAll(",", "%2C"); String intolerances = object.getJSONObject("query").getString("intolerances").replaceAll(" ", "+") .replaceAll(",", "%2C"); String maxCalories = object.getJSONObject("query").getString("maxCalories"); String maxCarbs = object.getJSONObject("query").getString("maxCarbs"); String maxFat = object.getJSONObject("query").getString("maxFat"); String maxProtein = object.getJSONObject("query").getString("maxProtein"); String minCalories = object.getJSONObject("query").getString("minCalories"); String minCarbs = object.getJSONObject("query").getString("minCarbs"); String minFat = object.getJSONObject("query").getString("minFat"); String minProtein = object.getJSONObject("query").getString("minProtein"); String query = object.getJSONObject("query").getString("querywords").replaceAll(" ", "+").replaceAll(",", "%2C"); String type = "".replaceAll(" ", "+"); String disease = object.getString("disease"); //System.out.println(disease); if (query.length() > 1) { query = query.substring(1);//from w w w. j a v a 2 s . co m } /* ZoneId zoneIdParis = ZoneId.of( "America/New_York" ); LocalDateTime dateTime = LocalDateTime.now( zoneIdParis); String temp=dateTime.toString().split("T")[1]; System.out.println(temp); */ @SuppressWarnings("deprecation") int hours = new Date().getHours(); System.out.println("hours: " + hours); if (hours >= 5 && hours <= 10) { type = type + "breakfast"; } else if (hours > 10 && hours <= 12) { type = type + "brunch"; } else if (hours > 12 && hours <= 15 || hours > 18 && hours <= 23) { type = type + "main+course"; } else if (hours > 23 || hours < 5 || hours > 15 && hours <= 18) { type = type + "snacks"; } System.out.println(); /* double weight = Integer.parseInt(object.getString("weight")); String unit_weight=object.getString("weightIN"); if(unit_weight.equals("pounds")){ weight=weight/2.2; } double height = 0.0; String unit_height=object.getString("heightIN"); if (unit_height.equals("ft")) { height=height/2.2; }*/ /* double bmi = 0.0; bmi = ((weight * 703)/(height * height)); System.out.println("BMI VALUES"); System.out.println("Underweight: Under 18.5"); System.out.println("Normal: 18.5-24.9 "); System.out.println("Overweight: 25-29.9"); System.out.println("Obese: 30 or over"); */ ////////////////////////////////////////////// double weight = Double.parseDouble(object.getString("weight")); String unit_weight = object.getString("weightIN"); if (unit_weight.equals("pounds")) { weight = weight * 0.45; } System.out.println(weight); double height = Double.parseDouble(object.getString("height")); String unit_height = object.getString("heightIN"); System.out.println(height); if (unit_height.equals("ft")) { height = height * 0.025; } System.out.println(height); double bmi = 0.0; bmi = ((weight) / (height * height)); int age = Integer.parseInt(object.getString("age")); String Gender = object.getString("gender"); double[] maleActivities = { 1, 1.11, 1.26, 1.48 }; double[] femaleActivities = { 1, 1.12, 1.27, 1.45 }; //String[] PhysicalActivity={"Sedentary (no exercise)","Low active (walks about 2 miles daily at 3-4 mph)","Active (walks about 7 miles daily at 3-4 mph)","Very active (walks about 17 miles daily at 3-4 mph)"}; double calories = 0.0; double userMaxCal = Double.parseDouble(maxCalories); if (Gender.equals("male")) { calories = 662 - (6.91 * age) + (maleActivities[Integer.parseInt(object.getString("activityLevel"))] * 15.91 * weight) + (539.6 * height); } else { calories = 354 - (6.91 * age) + (femaleActivities[Integer.parseInt(object.getString("activityLevel"))] * 9.36 * weight) + (726 * height); } if (userMaxCal > calories) { // maxCalories=String.valueOf(calories); } //List<String> words= new ArrayList<String>(); //words= getSuggestions("Olrves", 2); //System.out.println(words.toString()); //////////////////////////////////////////////////////////////////// //original recipes //String url = "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/searchComplex?cuisine="+cuisine+"&excludeIngredients="+excludeIngredients+"&includeIngredients="+includeIngredients+"&intolerances="+intolerances+"&limitLicense=false&maxCalories="+maxCalories+"+&maxCarbs="+maxCarbs+"&maxFat="+maxFat+"&maxProtein="+maxProtein+"&minCalories="+minCalories+"&minCarbs="+minCarbs+"&minFat="+minFat+"&minProtein="+minProtein+"&number=100&offset=0&query="+query+"&ranking=1&type="+type; String url = "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/searchComplex?cuisine=" + cuisine + "&fillIngredients=false"; if (intolerances != "") { url += "&intolerances=" + intolerances; } if (includeIngredients != "") { url += "&includeIngredients=" + includeIngredients; } else { url += "&includeIngredients=salt"; } url += "&limitLicense=false&maxCalories=" + maxCalories + "&maxCarbs=" + maxCarbs + "&maxFat=" + maxFat + "&maxProtein=" + maxProtein + "&minCalories=" + minCalories + "&minCarbs=" + minCarbs + "&minFat=" + minFat + "&minProtein=" + minProtein + "&number=100&offset=0&query=" + query + "&ranking=1" + "&type=" + type; //System.out.println("url : " + url); HttpResponse<String> response = Unirest.get(url) //EzPVzV3OIImshUC16NzTUL4Q9zE5p1fS8uIjsnHrZlqZDU38BN .header("X-Mashape-Key", "q8OegLa2iqmshvbsYklWvajeDcqZp1e63fSjsnmhLIw9xoIlw1").asString(); System.out.println( "**********************************Just before printing url********************************"); System.out.println("url : " + url); System.out.println("response.getBody() : " + response.getBody()); System.out.println( "**********************************Just after printing url********************************"); //String filename="air_"+timestamp+".json"; //FileWriter filewriter = new FileWriter(filename); //filewriter.write(response.getBody().toString()); //filewriter.write(response.getBody().toString()); //filewriter.close(); //FileReader filereader = new FileReader(filename); //BufferedReader br = new BufferedReader(filereader); //System.out.println(br.readLine()); //JSONObject a = new JSONObject(br.readLine()); //System.out.println(a); //JSONArray getArray = a.getJSONArray("results"); ArrayList<String> al = new ArrayList<>(); JSONObject res = new JSONObject(response.getBody().toString()); org.json.JSONArray recipes = res.getJSONArray("results"); System.out.println(recipes.toString()); for (int i = 0; i < recipes.length(); i++) { JSONObject ids = recipes.getJSONObject(i); //System.out.println(ids.get("id").toString()); al.add(ids.get("id").toString()); } ArrayList<HashMap<String, Float>> xmlresult = new ArrayList<HashMap<String, Float>>(); System.out.println("*****************************before xmlParser****************************"); XMLParser xmlParse = new XMLParser(); xmlresult = xmlParse.xmlparser(disease); System.out.println("*****************************after xmlParser****************************"); //System.out.println(xmlresult.get(0).toString()); //System.out.println(xmlresult.get(1).toString()); //System.out.println(response.getBody()); System.out.println("al :" + al); System.out.println("xmlResult : " + xmlresult); return (JsonParser.jsonparser(al, xmlresult, recipes, disease)); }
From source file:no.opentech.shoppinglist.file.JSONHandler.java
public String createJSONFromItemList(ArrayList<Item> itemList) { JSONArray jsonItems = new JSONArray(); try {//from w ww . ja va2s . c om int i = 0; for (Item item : itemList) { log.debug("JSONifying " + item.getName()); jsonItems.put(i, item.getName()); jsonItems.put(1 + i, item.getDescription()); jsonItems.put(2 + i, item.getUsageCounter()); jsonItems.put(3 + i, item.getNumberInLine()); jsonItems.put(4 + i, Utils.getTimeStamp(item.getFirstSeen())); jsonItems.put(5 + i, Utils.getTimeStamp(item.getLastSeen())); i += 6; } } catch (JSONException e) { return null; } return jsonItems.toString(); }