List of usage examples for org.json JSONArray JSONArray
public JSONArray()
From source file:com.watabou.pixeldungeon.utils.Bundle.java
public void put(String key, Collection<? extends Bundlable> collection) { JSONArray array = new JSONArray(); for (Bundlable object : collection) { Bundle bundle = new Bundle(); bundle.put(CLASS_NAME, object.getClass().getName()); object.storeInBundle(bundle);// ww w. j a va 2s . c o m array.put(bundle.data); } try { data.put(key, array); } catch (JSONException e) { } }
From source file:com.esri.squadleader.model.GeoPackageReader.java
private static List<Layer> getTablesAsLayers(List<GeopackageFeatureTable> tables, Set<Geometry.Type> types, Renderer renderer) {/*from w w w. j a v a 2 s. c o m*/ List<Layer> layers = new ArrayList<Layer>(tables.size()); for (GeopackageFeatureTable table : tables) { if (types.contains(table.getGeometryType())) { final FeatureLayer layer = new FeatureLayer(table); JSONObject jsonObject = new JSONObject(); JSONArray fieldsArray = new JSONArray(); try { for (Field field : table.getFields()) { fieldsArray.put(new JSONObject(Field.toJson(field))); } jsonObject.put("fields", fieldsArray); LayerServiceInfo layerInfo = LayerServiceInfo .fromJson(new JsonFactory().createJsonParser(jsonObject.toString())); layer.getPopupInfo(0).setLayer(layerInfo); } catch (Exception e) { Log.e(TAG, "Could not create LayerServiceInfo for FeatureLayer for table " + table.getTableName(), e); } layer.setRenderer(renderer); layer.setName(table.getTableName()); layers.add(layer); } } return layers; }
From source file:ai.susi.mind.SusiSkill.java
public static JSONObject answerSkill(String[] phrases, String condition, String[] answers, boolean prior) { JSONObject json = new JSONObject(true); // write phrases JSONArray p = new JSONArray(); json.put("phrases", p); for (String phrase : phrases) p.put(SusiPhrase.simplePhrase(phrase.trim(), prior)); // write conditions (if any) if (condition != null && condition.length() > 0) { JSONArray c = new JSONArray(); json.put("process", c); c.put(SusiInference.simpleMemoryProcess(condition)); }//from w w w . j a v a 2 s.c o m // write actions JSONArray a = new JSONArray(); json.put("actions", a); a.put(SusiAction.answerAction(answers)); return json; }
From source file:ai.susi.mind.SusiSkill.java
/** * if no keys are given, we compute them from the given phrases * @param phrases//from w w w .ja va 2 s .c o m * @return */ private static JSONArray computeKeysFromPhrases(List<SusiPhrase> phrases) { Set<String> t = new LinkedHashSet<>(); // create a list of token sets from the phrases List<Set<String>> ptl = new ArrayList<>(); final AtomicBoolean needsCatchall = new AtomicBoolean(false); phrases.forEach(phrase -> { Set<String> s = new HashSet<>(); for (String token : SPACE_PATTERN.split(phrase.getPattern().toString())) { String m = SusiPhrase.extractMeat(token.toLowerCase()); if (m.length() > 1) s.add(m); } // if there is no meat inside, it will not be possible to access the skill without the catchall skill, so remember that if (s.size() == 0) needsCatchall.set(true); ptl.add(s); }); // this is a kind of emergency case where we need a catchall skill because otherwise we cannot access one of the phrases JSONArray a = new JSONArray(); if (needsCatchall.get()) return a.put(CATCHALL_KEY); // collect all token ptl.forEach(set -> set.forEach(token -> t.add(token))); // if no tokens are available, return the catchall key if (t.size() == 0) return a.put(CATCHALL_KEY); // make a copy to make it possible to use the original key set again Set<String> tc = new LinkedHashSet<>(); t.forEach(c -> tc.add(c)); // remove all token that do not appear in all phrases ptl.forEach(set -> { Iterator<String> i = t.iterator(); while (i.hasNext()) if (!set.contains(i.next())) i.remove(); }); // if no token is left, use the original tc set and add all keys if (t.size() == 0) { tc.forEach(c -> a.put(c)); return a; } // use only the first token, because that appears in all the phrases return new JSONArray().put(t.iterator().next()); }
From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java
private static void addRepeatToXml(Element root, Repeat repeat, JSONObject in, String section, String permlevel) throws JSONException, UnderlyingStorageException { if (repeat.isServicesReadOnly()) { // Omit fields that are read-only in the services layer. log.debug("Omitting services-readonly repeat: " + repeat.getID()); return;/*from w ww.ja va 2 s . c om*/ } Element element = root; if (repeat.hasServicesParent()) { for (String path : repeat.getServicesParent()) { if (path != null) { element = element.addElement(path); } } } else if (!repeat.getXxxServicesNoRepeat()) { // Sometimes the UI is ahead of the services layer element = root.addElement(repeat.getServicesTag()); } Object value = null; if (repeat.getXxxUiNoRepeat()) { // and sometimes the Servcies ahead of teh UI FieldSet[] children = repeat.getChildren(permlevel); if (children.length == 0) return; addFieldSetToXml(element, children[0], in, section, permlevel); return; } else { value = in.opt(repeat.getID()); } if (value == null || ((value instanceof String) && StringUtils.isBlank((String) value))) return; if (value instanceof String) { // And sometimes the services ahead of the UI JSONArray next = new JSONArray(); next.put(value); value = next; } if (!(value instanceof JSONArray)) throw new UnderlyingStorageException( "Bad JSON in repeated field: must be string or array for repeatable field" + repeat.getID()); JSONArray array = (JSONArray) value; //reorder the list if it has a primary //XXX this will be changed when service layer accepts non-initial values as primary if (repeat.hasPrimary()) { Stack<Object> orderedarray = new Stack<Object>(); for (int i = 0; i < array.length(); i++) { Object one_value = array.get(i); if (one_value instanceof JSONObject) { if (((JSONObject) one_value).has("_primary")) { if (((JSONObject) one_value).getBoolean("_primary")) { orderedarray.add(0, one_value); continue; } } } orderedarray.add(one_value); } JSONArray newarray = new JSONArray(); int j = 0; for (Object obj : orderedarray) { newarray.put(j, obj); j++; } array = newarray; } Element repeatelement = element; for (int i = 0; i < array.length(); i++) { if (repeat.hasServicesParent()) { repeatelement = element.addElement(repeat.getServicesTag()); } Object one_value = array.get(i); if (one_value == null || ((one_value instanceof String) && StringUtils.isBlank((String) one_value))) continue; if (one_value instanceof String) { // Assume it's just the first entry (useful if there's only one) FieldSet[] fs = repeat.getChildren(permlevel); if (fs.length < 1) continue; JSONObject d1 = new JSONObject(); d1.put(fs[0].getID(), one_value); addFieldSetToXml(repeatelement, fs[0], d1, section, permlevel); } else if (one_value instanceof JSONObject) { List<FieldSet> children = getChildrenWithGroupFields(repeat, permlevel); for (FieldSet fs : children) addFieldSetToXml(repeatelement, fs, (JSONObject) one_value, section, permlevel); } } element = repeatelement; }
From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java
private static JSONArray extractRepeatData(Element container, FieldSet f, String permlevel) throws JSONException { JSONArray newout = new JSONArray(); // Build index so that we can see when we return to the start List<String> fields = FieldListFROMConfig(f, permlevel); Map<String, Integer> field_index = new HashMap<String, Integer>(); for (int i = 0; i < fields.size(); i++) { field_index.put(fields.get(i), i); }/* w w w . j av a2 s . c om*/ JSONObject test = new JSONObject(); JSONArray testarray = new JSONArray(); // Iterate through Integer prev = Integer.MAX_VALUE; for (Object node : container.selectNodes("*")) { if (!(node instanceof Element)) continue; Integer next = field_index.get(((Element) node).getName()); if (next == null) continue; if (next != prev) { // Must be a new instance if (test.length() > 0) { newout.put(test); } test = new JSONObject(); testarray = new JSONArray(); } prev = next; testarray.put((Element) node); test.put(((Element) node).getName(), testarray); } if (test.length() > 0) { newout.put(test); } return newout; }
From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java
private static JSONArray addRepeatedNodeToJson(Element container, Repeat f, String permlevel, JSONObject tempSon) throws JSONException { JSONArray node = new JSONArray(); List<FieldSet> children = getChildrenWithGroupFields(f, permlevel); JSONArray elementlist = extractRepeatData(container, f, permlevel); JSONObject siblingitem = new JSONObject(); for (int i = 0; i < elementlist.length(); i++) { JSONObject element = elementlist.getJSONObject(i); Iterator<?> rit = element.keys(); while (rit.hasNext()) { String key = (String) rit.next(); JSONArray arrvalue = new JSONArray(); for (FieldSet fs : children) { if (fs instanceof Repeat && ((Repeat) fs).hasServicesParent()) { if (!((Repeat) fs).getServicesParent()[0].equals(key)) { continue; }/* ww w.j a v a 2s. co m*/ Object value = element.get(key); arrvalue = (JSONArray) value; } else { if (!fs.getID().equals(key)) { continue; } Object value = element.get(key); arrvalue = (JSONArray) value; } if (fs instanceof Field) { for (int j = 0; j < arrvalue.length(); j++) { JSONObject repeatitem = new JSONObject(); //XXX remove when service layer supports primary tags if (f.hasPrimary() && j == 0) { repeatitem.put("_primary", true); } Element child = (Element) arrvalue.get(j); Object val = child.getText(); Field field = (Field) fs; String id = field.getID(); if (f.asSibling()) { addExtraToJson(siblingitem, child, field, tempSon); if (field.getDataType().equals("boolean")) { siblingitem.put(id, (Boolean.parseBoolean((String) val) ? true : false)); } else { siblingitem.put(id, val); } } else { addExtraToJson(repeatitem, child, field, tempSon); if (field.getDataType().equals("boolean")) { repeatitem.put(id, (Boolean.parseBoolean((String) val) ? true : false)); } else { repeatitem.put(id, val); } node.put(repeatitem); } tempSon = addtemp(tempSon, fs.getID(), child.getText()); } } else if (fs instanceof Group) { JSONObject tout = new JSONObject(); JSONObject tempSon2 = new JSONObject(); Group rp = (Group) fs; addRepeatToJson(tout, container, rp, permlevel, tempSon2, "", ""); if (f.asSibling()) { JSONArray a1 = tout.getJSONArray(rp.getID()); JSONObject o1 = a1.getJSONObject(0); siblingitem.put(fs.getID(), o1); } else { JSONObject repeatitem = new JSONObject(); repeatitem.put(fs.getID(), tout.getJSONArray(rp.getID())); node.put(repeatitem); } tempSon = addtemp(tempSon, rp.getID(), tout.getJSONArray(rp.getID())); //log.info(f.getID()+":"+rp.getID()+":"+tempSon.toString()); } else if (fs instanceof Repeat) { JSONObject tout = new JSONObject(); JSONObject tempSon2 = new JSONObject(); Repeat rp = (Repeat) fs; addRepeatToJson(tout, container, rp, permlevel, tempSon2, "", ""); if (f.asSibling()) { siblingitem.put(fs.getID(), tout.getJSONArray(rp.getID())); } else { JSONObject repeatitem = new JSONObject(); repeatitem.put(fs.getID(), tout.getJSONArray(rp.getID())); node.put(repeatitem); } tempSon = addtemp(tempSon, rp.getID(), tout.getJSONArray(rp.getID())); //log.info(f.getID()+":"+rp.getID()+":"+tempSon.toString()); } } } } if (f.asSibling()) { node.put(siblingitem); } return node; }
From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java
private static void addRepeatToJson(JSONObject out, Element root, Repeat f, String permlevel, JSONObject tempSon, String csid, String ims_url) throws JSONException { if (f.getXxxServicesNoRepeat()) { //not a repeat in services yet but is a repeat in UI FieldSet[] fields = f.getChildren(permlevel); if (fields.length == 0) return; JSONArray members = new JSONArray(); JSONObject data = new JSONObject(); addFieldSetToJson(data, root, fields[0], permlevel, tempSon, csid, ims_url); members.put(data);//from www.j a v a 2s . c om out.put(f.getID(), members); return; } String nodeName = f.getServicesTag(); if (f.hasServicesParent()) { nodeName = f.getfullID(); //XXX hack because of weird repeats in accountroles permroles etc if (f.getServicesParent().length == 0) { nodeName = f.getID(); } } List<?> nodes = root.selectNodes(nodeName); if (nodes.size() == 0) {// add in empty primary tags and arrays etc to help UI if (f.asSibling()) { JSONObject repeated = new JSONObject(); if (f.hasPrimary()) { repeated.put("_primary", true); } if (!out.has(f.getID())) { JSONArray temp = new JSONArray(); out.put(f.getID(), temp); } out.getJSONArray(f.getID()).put(repeated); } else { JSONArray repeatitem = new JSONArray(); out.put(f.getID(), repeatitem); } return; } // Only first element is important in container //except when we have repeating items int pos = 0; for (Object repeatcontainer : nodes) { pos++; Element container = (Element) repeatcontainer; if (f.asSibling()) { JSONArray repeatitem = addRepeatedNodeToJson(container, f, permlevel, tempSon); JSONArray temp = new JSONArray(); if (!out.has(f.getID())) { out.put(f.getID(), temp); } for (int arraysize = 0; arraysize < repeatitem.length(); arraysize++) { JSONObject repeated = repeatitem.getJSONObject(arraysize); if (f.hasPrimary() && pos == 1) { repeated.put("_primary", true); } out.getJSONArray(f.getID()).put(repeated); } } else { JSONArray repeatitem = addRepeatedNodeToJson(container, f, permlevel, tempSon); out.put(f.getID(), repeatitem); } } }
From source file:com.phonegap.Storage.java
/** * Process query results./*from w w w .j ava2s. c o m*/ * * @param cur Cursor into query results * @param tx_id Transaction id */ public void processResults(Cursor cur, String tx_id) { String result = "[]"; // If query result has rows if (cur.moveToFirst()) { JSONArray fullresult = new JSONArray(); String key = ""; String value = ""; int colCount = cur.getColumnCount(); // Build up JSON result object for each row do { JSONObject row = new JSONObject(); try { for (int i = 0; i < colCount; ++i) { key = cur.getColumnName(i); value = cur.getString(i); row.put(key, value); } fullresult.put(row); } catch (JSONException e) { e.printStackTrace(); } } while (cur.moveToNext()); result = fullresult.toString(); } // Let JavaScript know that there are no more rows this.sendJavascript("droiddb.completeQuery('" + tx_id + "', " + result + ");"); }
From source file:server.http.system.SysInfo.java
@Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("application/json;charset=UTF-8"); try (PrintWriter out = res.getWriter()) { JSONObject root = new JSONObject(); try {/*www .j a va2 s .com*/ JSONObject net = new JSONObject(); net.put("Download_B", SystemInformation.DOWNLOAD); net.put("Upload_B", SystemInformation.UPLOAD); root.put("Network_B", net); // JSONObject netF = new JSONObject(); // netF.put("Download_Fmt", SystemInformation.DOWNLOAD_FORMAT); // netF.put("Upload_Fmt", SystemInformation.UPLOAD_FORMAT); // root.put("Network_Fmt", netF); // ------------------------------------------- Cpu Sys JSONObject cpuSys = new JSONObject(); int k = 0; for (int i : SystemInformation.CPU_USAGE) { cpuSys.put("Usage" + (k++), i); } cpuSys.put("UsageAll", SystemInformation.CPU_USAGE_ALL); root.put("CpuSys_%", cpuSys); // ------------------------------------------- Cpu App JSONObject cpuApp = new JSONObject(); cpuApp.put("SysUsage", SystemInformation.CPU_USAGE_SYSTEM); cpuApp.put("AppUsage", SystemInformation.CPU_USAGE_APP); root.put("CpuApp_%", cpuApp); // ------------------------------------------- Thread Count App JSONObject appThread = new JSONObject(); appThread.put("Count", SystemInformation.THREAD_COUNT); appThread.put("DaemonCount", SystemInformation.THREAD_COUNT_DAEMON); appThread.put("PeakCount", SystemInformation.THREAD_COUNT_PEAK); root.put("AppThread", appThread); // ------------------------------------------- Ram App JSONObject ramApp = new JSONObject(); ramApp.put("Total", SystemInformation.RAM_TOTAL_MB); ramApp.put("Max", SystemInformation.RAM_MAX_MB); ramApp.put("Free", SystemInformation.RAM_FREE_MB); root.put("RamApp_MB", ramApp); // ------------------------------------------- Ram Sys JSONObject ramSys = new JSONObject(); ramSys.put("PhysTotal", SystemInformation.TOTAL_PHYSICAL_MEMORY_SIZE_MB); ramSys.put("PhysFree", SystemInformation.FREE_PHYSICAL_MEMORY_SIZE_MB); ramSys.put("SwapTotal", SystemInformation.TOTAL_SWAP_SPACE_SIZE_MB); ramSys.put("SwapFree", SystemInformation.FREE_SWAP_SPACE_SIZE_MB); root.put("RamSys_MB", ramSys); // ------------------------------------------- Hdd Sys JSONArray hddSys = new JSONArray(); for (int i = 0; i < SystemInformation.HDD_NAME.size(); i++) { JSONObject hdd = new JSONObject(); hdd.put("Name", SystemInformation.HDD_NAME.get(i)); hdd.put("Total", SystemInformation.HDD_TOTAL_SPACE_GB.get(i)); hdd.put("Free", SystemInformation.HDD_FREE_SPACE_GB.get(i)); hddSys.put(hdd); } root.put("HddSys_GB", hddSys); // ------------------------------------------- Add Root } catch (Exception e) { out.print("error"); } out.print(root.toString(4));//036670221 } }