List of usage examples for org.json JSONObject toJSONArray
public JSONArray toJSONArray(JSONArray names) throws JSONException
From source file:com.nosoop.json.VDF.java
/** * Recursively searches for JSONObjects, checking if they should be * formatted as arrays, then converted.//w ww . j a v a 2 s . c o m * * @param object An input JSONObject converted from VDF. * @return JSONObject containing the input JSONObject with objects changed * to arrays where applicable. * @throws JSONException */ private static JSONObject convertVDFArrays(JSONObject object) throws JSONException { JSONObject resp = new JSONObject(); if (!object.keys().hasNext()) { return resp; } for (@SuppressWarnings("unchecked") Iterator<String> iter = object.keys(); iter.hasNext();) { String name = iter.next(); JSONObject thing = object.optJSONObject(name); if (thing != null) { // Note: Empty JSONObjects are also treated as arrays. if (containsVDFArray(thing)) { @SuppressWarnings("unchecked") Iterator<String> iter2 = thing.keys(); List<String> sortingKeys = new ArrayList<String>(); while (iter2.hasNext()) sortingKeys.add(iter2.next()); Collections.sort(sortingKeys, new Comparator<String>() { // Integers-as-strings comparator. @Override public int compare(String t, String t1) { int i = Integer.parseInt(t), i1 = Integer.parseInt(t1); return i - i1; } }); JSONArray sortedKeys = new JSONArray(sortingKeys); if (sortedKeys.length() > 0) { JSONArray sortedObjects = thing.toJSONArray(sortedKeys); for (int i = 0; i < sortedObjects.length(); i++) { JSONObject arrayObject = sortedObjects.getJSONObject(i); /** * See if any values are also JSONObjects that * should be arrays. */ sortedObjects.put(i, convertVDFArrays(arrayObject)); } /** * If this JSONObject represents a non-empty array in * VDF format, convert it to a JSONArray. */ resp.put(name, sortedObjects); } else { /** * If this JSONObject represents an empty array, give it * an empty JSONArray. */ resp.put(name, new JSONArray()); } } else { /** * If this JSONObject is not a VDF array, see if its values * are before adding. */ resp.put(name, convertVDFArrays(thing)); } } else { /** * It's a plain data value. Add it in. */ resp.put(name, object.get(name)); } } /** * Return the converted JSONObject. */ return resp; }
From source file:org.official.json.CDL.java
/** * Produce a comma delimited text from a JSONArray of JSONObjects using * a provided list of names. The list of names is not included in the * output./*from w w w . j a v a 2 s . c o m*/ * @param names A JSONArray of strings. * @param ja A JSONArray of JSONObjects. * @return A comma delimited text. * @throws JSONException */ public static String toString(JSONArray names, JSONArray ja) throws JSONException { if (names == null || names.length() == 0) { return null; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < ja.length(); i += 1) { JSONObject jo = ja.optJSONObject(i); if (jo != null) { sb.append(rowToString(jo.toJSONArray(names))); } } return sb.toString(); }