List of usage examples for org.json JSONArray put
public JSONArray put(Object value)
From source file:de.luhmer.owncloudnewsreader.reader.owncloud.OwnCloudReaderMethods.java
private static String buildIdsToJSONArray(List<String> ids) { try {//w ww. ja va 2 s. c o m JSONArray jArr = new JSONArray(); for (String id : ids) jArr.put(Integer.parseInt(id)); JSONObject jObj = new JSONObject(); jObj.put("items", jArr); return jObj.toString(); } catch (Exception ex) { ex.printStackTrace(); } return null; }
From source file:de.luhmer.owncloudnewsreader.reader.owncloud.OwnCloudReaderMethods.java
private static String buildIdsToJSONArrayWithGuid(HashMap<String, String> items) { try {/*from www . ja v a 2 s . c om*/ JSONArray jArr = new JSONArray(); for (Map.Entry<String, String> entry : items.entrySet()) { JSONObject jOb = new JSONObject(); jOb.put("feedId", Integer.parseInt(entry.getValue())); jOb.put("guidHash", entry.getKey()); jArr.put(jOb); } JSONObject jObj = new JSONObject(); jObj.put("items", jArr); return jObj.toString(); } catch (Exception ex) { ex.printStackTrace(); } return null; }
From source file:org.protorabbit.json.JSONUtil.java
public static void concatJSONArrays(JSONArray parent, JSONArray child) throws JSONException { for (int i = 0; i < child.length(); i++) { parent.put(child.get(i)); }/*from ww w .j av a 2 s.c o m*/ }
From source file:org.uiautomation.ios.server.application.IOSApplication.java
public JSONObject getTranslations(String name) throws JSONException { JSONObject l10n = new JSONObject(); l10n.put("matches", 0); if (name != null && !name.isEmpty() && !"null".equals(name)) { try {/*from w w w . ja v a 2 s . c o m*/ List<ContentResult> results = getPotentialMatches(name); int size = results.size(); if (size != 0) { l10n.put("matches", size); l10n.put("key", results.get(0).getKey()); } JSONArray langs = new JSONArray(); for (AppleLocale language : getSupportedLanguages()) { JSONArray possibleMatches = new JSONArray(); for (ContentResult res : results) { possibleMatches.put(translate(res, language)); } JSONObject match = new JSONObject(); match.put(language.toString(), possibleMatches); langs.put(match); } l10n.put("langs", langs); } catch (Exception e) { e.printStackTrace(); } } return l10n; }
From source file:com.imos.sample.pi.TemperatureSensor.java
public void pythonTemperatureSensor() { try {/*from w w w . java2 s. c o 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:edu.stanford.mobisocial.dungbeetle.feed.objects.AppReferenceObj.java
public static DbObject forFixedMembership(Bundle params, String[] membership, String feedName, String groupUri) {//from w w w . jav a 2s . c om JSONObject json = new JSONObject(); try { JSONArray mship = new JSONArray(); for (String m : membership) { mship.put(m); } json.put(PACKAGE_NAME, params.getString(PACKAGE_NAME)); json.put(OBJ_INTENT_ACTION, params.getString(OBJ_INTENT_ACTION)); // todo: pendingIntent? parcelable? json.put(Multiplayer.OBJ_MEMBERSHIP, mship); json.put(DbObject.CHILD_FEED_NAME, feedName); json.put(GROUP_URI, groupUri); } catch (JSONException e) { } return new DbObject(TYPE, json); }
From source file:com.yoloci.fileupload.BundleJSONConverter.java
public static JSONObject convertToJSON(Bundle bundle) throws JSONException { JSONObject json = new JSONObject(); for (String key : bundle.keySet()) { Object value = bundle.get(key); if (value == null) { // Null is not supported. continue; }/*from www . j a va 2 s . c om*/ // Special case List<String> as getClass would not work, since List is an interface if (value instanceof List<?>) { JSONArray jsonArray = new JSONArray(); @SuppressWarnings("unchecked") List<String> listValue = (List<String>) value; for (String stringValue : listValue) { jsonArray.put(stringValue); } json.put(key, jsonArray); continue; } // Special case Bundle as it's one way, on the return it will be JSONObject if (value instanceof Bundle) { json.put(key, convertToJSON((Bundle) value)); continue; } Setter setter = SETTERS.get(value.getClass()); if (setter == null) { throw new IllegalArgumentException("Unsupported type: " + value.getClass()); } setter.setOnJSON(json, key, value); } return json; }
From source file:org.ohmage.request.Request.java
/** * Returns a String representation of the failure message that would be * returned to a user if this request has failed. All requests have a * default failure message, so this will always return some error message; * however, if the request has not yet failed, this result is meaningless. * //from w ww. j a v a2s . c o m * @return A String representation of the current failure message for this * request. */ public String getFailureMessage() { String result; try { // Use the annotator's message to build the response. JSONObject resultJson = new JSONObject(); resultJson.put(JSON_KEY_RESULT, RESULT_FAILURE); // FIXME: We no longer have multiple error messages per failed // response, so we need to get rid of this unnecessary array. JSONArray jsonArray = new JSONArray(); jsonArray.put(annotator.toJsonObject()); resultJson.put(JSON_KEY_ERRORS, jsonArray); result = resultJson.toString(); } catch (JSONException e) { // If we can't even build the failure message, write a hand- // written message as the response. LOGGER.error("An error occurred while building the failure JSON response.", e); result = RESPONSE_ERROR_JSON_TEXT; } return result; }
From source file:org.archiviststoolkit.plugin.utils.CodeViewerDialog.java
/** * Method to set the ASpace client for running test on multiple records * *//* w ww . ja v a2 s . c o m*/ public void setUpMultipleRecordTest() { testMultipleRecords = true; // now create a json object which has a list of record URI for testing // We could just use a string, but first creating a json array makes // formatting the string easier and of course assures we are creating // a valid json array. JSONArray recordsJA = new JSONArray(); recordsJA.put("/repositories/2"); recordsJA.put("/users/4"); recordsJA.put("/subjects/1"); recordsJA.put("/agents/families/1"); recordsJA.put("/agents/people/1"); recordsJA.put("/agents/corporate_entities/1"); recordsJA.put("/repositories/2/accessions/1"); recordsJA.put("/repositories/2/resources/1"); recordsJA.put("/repositories/2/archival_objects/1"); try { textArea.setText(recordsJA.toString(2)); } catch (Exception e) { textArea.setText("Problem "); } }
From source file:org.phoneremotecontrol.app.sms.SMSHttpWorker.java
private Response serveConversations() { Log.d(TAG, "Serving conversations ..."); List<Conversation> list = SMSUtils.getSMSThreadIds(context); JSONArray conversationArray = new JSONArray(); File imagePath = new File(cacheDir, "img"); if (!imagePath.isDirectory()) { imagePath.mkdir();//from w ww .j a va 2 s. co m } for (Conversation c : list) { File contactImage = null; try { contactImage = copyContactImage(c.getContact(), imagePath); } catch (ContactException e) { Log.d(TAG, "Fail to copy contact image for " + e.getMessage()); } JSONObject jsonObject = null; try { jsonObject = c.toJSON(); if (contactImage != null) { jsonObject.put("imagePath", cacheLocation + "/img/" + contactImage.getName()); } } catch (JSONException e) { Log.e(TAG, "Unable to serialize JSON for " + c); } conversationArray.put(jsonObject); } String msg = conversationArray.toString(); Response response = new Response(msg); response.setMimeType("application/json"); return response; }