List of usage examples for org.json JSONArray put
public JSONArray put(Object value)
From source file:com.draekko.traypreferences.TraySharedPreferencesImpl.java
public void putStringSet(String key, @Nullable Set<String> values) { if (key == null || key.isEmpty()) { throw new IllegalArgumentException("invalid key parameter!"); }/*from ww w . ja va 2 s . c o m*/ notifyListeners(key); if (values == null || values.size() < 1) { appPreferences.put(key, null); return; } JSONArray jsonArray = new JSONArray(); for (String s : values) { jsonArray.put(s); } JSONObject json = new JSONObject(); try { json.put("stringset", jsonArray); String saved = json.toString(); appPreferences.put(key, saved); } catch (JSONException e) { e.printStackTrace(); appPreferences.put(key, null); } }
From source file:com.marketcloud.marketcloud.Orders.java
/** * Convert bidimensional array of items to JSONArray of items. * * @param array bidimensional array to convert * @return converted array/*from w w w. ja va2 s. c om*/ */ private JSONArray toJsonArray(Object[][] array) throws JSONException { JSONArray jsonArray = new JSONArray(); for (Object[] i : array) { JSONObject jsonObject = new JSONObject(); jsonObject.put("product_id", (int) i[0]); jsonObject.put("quantity", (int) i[1]); jsonArray.put(jsonObject); } return jsonArray; }
From source file:edu.txstate.dmlab.clusteringwiki.rest.SearchController.java
/** * Execute search/*from w ww . j ava 2 s. c o m*/ * @param service the service the user has chosen to execute query in * @param icwservice underlying ICWSearcher service to be used when searching * @param query query to be executed * @param numResults number of results to be retrieved * @param start first result to be retrieved * @param model * @return * @throws Exception */ @RequestMapping("/search/{service}/{icwservice}/{query}/{numResults}/{start}") public String search(@PathVariable("service") String service, @PathVariable("icwservice") String icwservice, @PathVariable("query") String query, @PathVariable("numResults") String numResults, @PathVariable("start") String start, Model model) throws Exception { ICWSearchResultCol search = null; try { search = doSearch(service, icwservice, query, numResults, start); } catch (Exception e) { search = new BaseCWSearchResultCol(); search.addError(e.getMessage()); model.addAttribute("search", search); return "searchResultsView"; } String clusterKey = KeyGenerator.getKey(); search.setClusterKey(clusterKey); JSONArray searchParams = new JSONArray(); searchParams.put(service); searchParams.put(icwservice); searchParams.put(query); searchParams.put(numResults); searchParams.put(start); model.addAttribute("search", search); return "searchResultsView"; }
From source file:org.apps8os.contextlogger3.android.clientframework.ActivityRecognitionService.java
private void handleActivityRecognitionResult(final ActivityRecognitionResult result) { Bundle data = new Bundle(); // Get the most probable activity DetectedActivity mostProbableActivity = result.getMostProbableActivity(); String activityName = ActivityType.getActivityTypeByReference(mostProbableActivity.getType()); data.putString("Activity", activityName); data.putString("ActivityConfidence", String.valueOf(mostProbableActivity.getConfidence())); try {/* w w w. java2 s.c om*/ List<DetectedActivity> daList = result.getProbableActivities(); if ((daList != null) && (!daList.isEmpty())) { JSONArray jsonArray = new JSONArray(); for (DetectedActivity da : daList) { JSONObject daObject = new JSONObject(); daObject.put("Activity", ActivityType.getActivityTypeByReference(da.getType())); daObject.put("ActivityConfidence", String.valueOf(da.getConfidence())); jsonArray.put(daObject); } if (jsonArray.length() > 0) { data.putString("ProbableActivities", jsonArray.toString()); } } } catch (Exception e) { Log.e(ActivityRecognitionService.class.getCanonicalName(), "error: ", e); String probableActivities = TextUtils.join("|", result.getProbableActivities()); data.putString("ProbableActivities", probableActivities); } data.putString("timestamp", String.valueOf(result.getTime())); Intent intent = new Intent(GoogleActivityRecognitionProbe.INTENT_ACTION); intent.putExtras(data); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent); }
From source file:edu.txstate.dmlab.clusteringwiki.sources.BaseCWSearchResultCol.java
/** * Create customized JSON representation of the object * @return// ww w.j av a2 s.c o m * @throws JSONException */ public JSONObject toJSON() throws JSONException { JSONObject j = new JSONObject(); j.put("clusterKey", clusterKey); j.put("dataSourceKey", dataSourceKey); j.put("dataSourceName", dataSourceName); j.put("service", service); j.put("totalResults", totalResults); j.put("returnedCount", returnedCount); j.put("firstPosition", firstPosition); if (results != null) { JSONArray a = new JSONArray(); for (ICWSearchResult r : results) a.put(r.toJSON()); j.put("results", a); } else j.put("results", JSONObject.NULL); j.put("errors", errors); return j; }
From source file:cn.sharesdk.analysis.util.PreferencesHelper.java
/** * save events' info to cached file//w w w . j a v a 2 s . com */ @Deprecated public void saveInfoToFile(String key, JSONObject object) { JSONObject existJSON = null; try { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && DeviceHelper .getInstance(context).checkPermissions("android.permission.WRITE_EXTERNAL_STORAGE")) { // Does a cached file exist File cacheRoot = new File(getSdcardPath(), packageName); if (!cacheRoot.exists()) { cacheRoot.mkdirs(); Ln.i("cacheRoot path", "no path"); } File cacheFile = new File(cacheRoot, "mobclick_agent_cached_" + packageName); if (!cacheFile.exists()) { cacheFile.createNewFile(); Ln.i("cacheFile path", "no path createNewFile"); } // Does any data in the cached file FileInputStream in = new FileInputStream(cacheFile); StringBuffer sb = new StringBuffer(); int i = 0; byte[] s = new byte[1024 * 4]; while ((i = in.read(s)) != -1) { sb.append(new String(s, 0, i)); } in.close(); if (sb.length() != 0) { existJSON = new JSONObject(sb.toString()); } else { existJSON = new JSONObject(); } if (existJSON.has(key)) { JSONArray newDataArray = existJSON.getJSONArray(key); Ln.i("SaveInfo", object + ""); newDataArray.put(object); } else { JSONArray newArray = new JSONArray(); newArray.put(0, object); existJSON.put(key, newArray); Ln.i("SaveInfo", "jsonobject" + existJSON); } Ln.i("SaveInfo", "save json data to the cached file!"); // save json data to the cached file FileOutputStream fileOutputStream = new FileOutputStream(cacheFile, false); fileOutputStream.write(existJSON.toString().getBytes()); fileOutputStream.flush(); fileOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.comcast.oscar.sql.queries.PacketCableSqlQuery.java
/** 4 variable ClassOfService subtypes 7 1.0 (4,'4',0,'ClassOfService','',0,variable,integer,1.0); s 1 1 ClassId uint8 1.0 (5,'1',4,'ClassId','',0,1,integer,1.0); s 2 4 MaxDownstreamRate uint32 1.0 (6,'2',4,'MaxDownstreamRate','',0,4,integer,1.0); s 3 4 MaxUpstreamRate uint32 1.0 (7,'3',4,'MaxUpstreamRate','',0,4,integer,1.0); s 4 1 UpstreamChannelPriority uint8 1.0 (8,'4',4,'UpstreamChannelPriority','',0,1,integer,1.0); s 5 4 MinUpstreamRate uint32 1.0 (9,'5',4,'MinUpstreamRate','',0,4,integer,1.0); s 6 2 MaxUpstreamBurst uint16 1.0 (10,'6',4,'MaxUpstreamBurst','',0,2,integer,1.0); s 7 1 CoSPrivacyEnable boolean 1.0 (11,'7',4,'CoSPrivacyEnable','',0,1,integer,1.0); <p>//from w w w .j a v a 2 s .com 24 variable UpstreamServiceFlow subtypes 28 1.1 (151,'24',0,'UpstreamServiceFlow','',0,variable,integer,1.1); s 1 2 SfReference uint16 1.1 (152,'1',151,'SfReference','',0,2,integer,1.1); s 4 variable SfClassName null_terminated_string 1.1 (153,'4',151,'SfClassName','',0,variable,integer,1.1); s 5 variable SfErrorEncoding subtypes 3 1.1 (154,'5',151,'SfErrorEncoding','',0,variable,integer,1.1); s s 1 1 ErroredParameter uint8 1.1 (155,'1',154,'ErroredParameter','',0,1,integer,1.1); s s 2 1 ErrorCode uint8 1.1 (156,'2',154,'ErrorCode','',0,1,integer,1.1); s s 3 variable ErrorMessage null_terminated_string 1.1 (157,'3',154,'ErrorMessage','',0,variable,integer,1.1); s 6 1 SfQosSetType uint8 1.1 (158,'6',151,'SfQosSetType','',0,1,integer,1.1); <p> +------------------------------+----------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------------------+----------------------+------+-----+---------+----------------+ | ID | int(10) unsigned | NO | PRI | NULL | auto_increment | | TYPE | smallint(5) unsigned | NO | | NULL | | | PARENT_ID | int(10) unsigned | YES | | NULL | | | TLV_NAME | varchar(50) | NO | | NULL | | | TLV_DESCRIPTION | text | NO | | NULL | | | LENGTH_MIN | smallint(5) unsigned | NO | | NULL | | | LENGTH_MAX | smallint(5) unsigned | NO | | NULL | | | DATA_TYPE | varchar(50) | YES | | NULL | | | BYTE_LENGTH | tinyint(3) unsigned | NO | | NULL | | | MIN_SUPPORTED_DOCSIS_VERSION | varchar(50) | NO | | NULL | | +------------------------------+----------------------+------+-----+---------+----------------+ <p> * @param iRowID * @param iParentID * @param aliTlvEncodeHistory * @return JSONObject * @throws JSONException */ private JSONObject recursiveTlvDefinitionBuilder(Integer iRowID, Integer iParentID, ArrayList<Integer> aliTlvEncodeHistory) throws JSONException { Statement parentCheckStatement = null, getRowDefinitionStatement = null; ResultSet resultSetParentCheck = null, resultSetGetRowDefinition = null; aliTlvEncodeHistory.add(getTypeFromRowID(iParentID)); String sqlQuery; JSONObject tlvJsonObj = null; // This query will check for child rows that belong to a parent row sqlQuery = "SELECT " + " ID ," + " TYPE ," + " TLV_NAME," + " PARENT_ID " + "FROM " + " PACKET_CABLE_TLV_DEFINITION " + "WHERE " + " PARENT_ID = '" + iRowID + "'"; try { //Create statement parentCheckStatement = sqlConnection.createStatement(); //Get Result Set of Query resultSetParentCheck = parentCheckStatement.executeQuery(sqlQuery); } catch (SQLException e) { e.printStackTrace(); } /* ****************************************************************************************************** * If resultSet return an empty, this means that the row does not have a child and is not a Major TLV * *****************************************************************************************************/ try { if ((SqlConnection.getRowCount(resultSetParentCheck) == 0) && (iParentID != MAJOR_TLV)) { // This query will check for child rows that belong to a parent row sqlQuery = "SELECT * FROM " + " PACKET_CABLE_TLV_DEFINITION " + " WHERE ID = '" + iRowID + "'"; //Create statement to get Rows from ROW ID's getRowDefinitionStatement = sqlConnection.createStatement(); //Get Result Set resultSetGetRowDefinition = getRowDefinitionStatement.executeQuery(sqlQuery); //Advance to next index in result set, this is needed resultSetGetRowDefinition.next(); /************************************************* * Assemble JSON OBJECT *************************************************/ tlvJsonObj = new JSONObject(); tlvJsonObj.put(Dictionary.TYPE, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_TYPE)); tlvJsonObj.put(Dictionary.TLV_NAME, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_TLV_NAME)); tlvJsonObj.put(Dictionary.LENGTH_MIN, resultSetGetRowDefinition.getInt(Dictionary.DB_TBL_COL_LENGTH_MIN)); tlvJsonObj.put(Dictionary.LENGTH_MAX, resultSetGetRowDefinition.getInt(Dictionary.DB_TBL_COL_LENGTH_MAX)); tlvJsonObj.put(Dictionary.SUPPORTED_VERSIONS, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_SUPPORTED_VERSIONS)); tlvJsonObj.put(Dictionary.DATA_TYPE, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_DATA_TYPE)); tlvJsonObj.put(Dictionary.ARE_SUBTYPES, false); tlvJsonObj.put(Dictionary.BYTE_LENGTH, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_BYTE_LENGTH)); aliTlvEncodeHistory.add(resultSetGetRowDefinition.getInt(Dictionary.DB_TBL_COL_TYPE)); tlvJsonObj.put(PacketCableSqlQueryConstants.PARENT_TYPE_LIST, aliTlvEncodeHistory); if (debug) System.out.println(tlvJsonObj.toString()); } else if (iParentID == MAJOR_TLV) { // This query will check for child rows that belong to a parent row sqlQuery = "SELECT * FROM " + " DOCSIS_TLV_DEFINITION " + " WHERE ID = '" + iRowID + "'"; getRowDefinitionStatement = sqlConnection.createStatement(); resultSetGetRowDefinition = getRowDefinitionStatement.executeQuery(sqlQuery); resultSetGetRowDefinition.next(); /************************************************* * Assemble JSON OBJECT *************************************************/ tlvJsonObj = new JSONObject(); tlvJsonObj.put(Dictionary.TYPE, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_TYPE)); tlvJsonObj.put(Dictionary.TLV_NAME, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_TLV_NAME)); tlvJsonObj.put(Dictionary.LENGTH_MIN, resultSetGetRowDefinition.getInt(Dictionary.DB_TBL_COL_LENGTH_MIN)); tlvJsonObj.put(Dictionary.LENGTH_MAX, resultSetGetRowDefinition.getInt(Dictionary.DB_TBL_COL_LENGTH_MAX)); tlvJsonObj.put(Dictionary.SUPPORTED_VERSIONS, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_SUPPORTED_VERSIONS)); tlvJsonObj.put(Dictionary.DATA_TYPE, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_DATA_TYPE)); tlvJsonObj.put(Dictionary.ARE_SUBTYPES, false); tlvJsonObj.put(Dictionary.BYTE_LENGTH, resultSetGetRowDefinition.getString(Dictionary.DB_TBL_COL_BYTE_LENGTH)); aliTlvEncodeHistory.add(resultSetGetRowDefinition.getInt(Dictionary.DB_TBL_COL_TYPE)); tlvJsonObj.put(PacketCableSqlQueryConstants.PARENT_TYPE_LIST, aliTlvEncodeHistory); if (debug) System.out.println(tlvJsonObj.toString()); } if (SqlConnection.getRowCount(resultSetParentCheck) > 0) { // This query will check for child rows that belong to a parent row sqlQuery = "SELECT " + " TYPE , " + " TLV_NAME," + " PARENT_ID" + " FROM " + " DOCSIS_TLV_DEFINITION " + " WHERE ID = '" + iRowID + "'"; try { Integer iParentIdTemp = null; JSONArray tlvJsonArray = new JSONArray(); while (resultSetParentCheck.next()) { iParentIdTemp = resultSetParentCheck.getInt("PARENT_ID"); ArrayList<Integer> aliTlvEncodeHistoryNext = new ArrayList<Integer>(); aliTlvEncodeHistoryNext.addAll(aliTlvEncodeHistory); if (debug) System.out.println("aliTlvEncodeHistoryNext: " + aliTlvEncodeHistoryNext); aliTlvEncodeHistoryNext.remove(aliTlvEncodeHistoryNext.size() - 1); //Keep processing each row using recursion until you get to to the bottom of the tree tlvJsonArray.put( recursiveTlvDefinitionBuilder(resultSetParentCheck.getInt(Dictionary.DB_TBL_COL_ID), iParentIdTemp, aliTlvEncodeHistoryNext)); } //Get Parent Definition tlvJsonObj = getRowDefinitionViaRowId(iParentIdTemp); tlvJsonObj.put(PacketCableSqlQueryConstants.SUBTYPE_ARRAY, tlvJsonArray); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return tlvJsonObj; }
From source file:com.imos.sample.pi.LedBlink.java
public void pythonTemperatureSensor() { try {//from w w w . j a v a 2s .c om 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(LedBlink.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.google.samples.apps.iosched.nearby.MetadataResolver.java
private static JSONObject createRequestObject(List<NearbyDevice> devices) { JSONObject jsonObj = new JSONObject(); try {/* w w w . j av a2 s. co m*/ JSONArray urlArray = new JSONArray(); for (int dIdx = 0; dIdx < devices.size(); dIdx++) { NearbyDevice device = devices.get(dIdx); JSONObject urlObject = new JSONObject(); urlObject.put("url", device.getUrl()); urlObject.put("rssi", device.getLastRSSI()); urlArray.put(urlObject); } JSONObject location = new JSONObject(); location.put("lat", 49.129837); location.put("lon", 120.38142); jsonObj.put("location", location); jsonObj.put("objects", urlArray); } catch (JSONException ex) { } return jsonObj; }
From source file:org.androidsoft.games.memory.kids.model.TileList.java
/** * Serialize the List//from w ww . j a v a2 s. c o m * @return The list as a String */ String serialize() { JSONArray array = new JSONArray(); for (Tile t : this) { array.put(t.json()); } return array.toString(); }