Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

In this page you can find the example usage for org.json JSONArray JSONArray.

Prototype

public JSONArray() 

Source Link

Document

Construct an empty JSONArray.

Usage

From source file:de.joinout.criztovyl.tools.json.JSONCollection.java

/**
 * Sets up a new JSON collection helper.
 * @param coll the {@link Collection}/*from w  w w . j  a  va 2  s. co  m*/
 * @param creator the {@link JSONCreator} for the generic class.
 */
public JSONCollection(Collection<T> coll, JSONCreator<T> creator) {
    this(creator);

    JSONArray array = new JSONArray();

    for (T t : coll)
        array.put(creator.canBeString() ? creator.string(t) : creator.getJSON(t));

    getJSON().put(getKey(), array);
}

From source file:com.imos.sample.pi.MotionSensor.java

public void pythonTemperatureSensor() {

    try {/*  ww  w. j  ava2 s.  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(MotionSensor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.jennifer.ui.chart.widget.LegendWidget.java

private JSONArray getLegendIcon(JSONObject brushObject) {
    JSONArray arr = new JSONArray();
    JSONArray data = JSONUtil.clone(brushObject.getJSONArray("target"));

    if (key != null && key.length() > 0) {
        data = chart.data();/*from w ww . ja v a2 s.  co  m*/
    }

    int count = data.length();

    for (int i = 0; i < count; i++) {
        String text = "";

        if (key != null && key.length() > 0) {
            text = chart.series(key).optString("text", data.getJSONObject(i).getString(key));
        } else {
            String target = data.getString(i);
            text = chart.series(target).optString("text", target);
        }

        double rectWidth = (fontWidth - 4) * text.length();
        double width = Math.min(rectWidth, fontHeight);
        double height = width;

        Transform group = root.group(new JSONObject().put("class", "legend icon"));

        Transform rect = group.rect(new JSONObject().put("x", 0).put("y", 0).put("width", width)
                .put("height", height).put("fill", chart.color(i, brushObject.optJSONArray("colors"))));

        group.text(new JSONObject().put("x", width + 4).put("y", fontHeight - 3) // 3 is top, bottom font margin
                .put("font-family", chart.theme("fontFamily")).put("font-size", chart.theme("legendFontSize"))
                .put("fill", chart.theme("legendFontColor")).put("text-anchor", "start")).textNode(text);

        arr.put(new JSONObject().put("width", width + 4 + rectWidth + (i == count - 1 ? 0 : 10))
                .put("height", height + 4).put("icon", group)

        );

    }

    return arr;
}

From source file:pt.webdetails.cpf.persistence.PersistenceEngine.java

public JSONObject query(String query, Map<String, Object> params) throws JSONException {
    JSONObject json = new JSONObject();

    try {//from   w w w  .j av  a2  s  .  com
        json.put("result", Boolean.TRUE);

        List<ODocument> result = executeQuery(query, params);
        if (result != null) {
            JSONArray arr = new JSONArray();
            for (ODocument resDoc : result) {
                arr.put(new JSONObject(resDoc.toJSON()));
            }
            json.put("object", arr);
        }
    } catch (ODatabaseException ode) {
        json.put("result", Boolean.FALSE);
        json.put("errorMessage", "DatabaseException: Review query");
        logger.error(getExceptionDescription(ode));

    }
    return json;
}

From source file:org.LexGrid.lexevs.metabrowser.helper.ChildPagingJsonConverter.java

/**
 * Builds the children./*from w ww. j a v a  2  s  . c  o  m*/
 * 
 * @param focusNode the focus node
 * @param page the page
 * @param levels the levels
 * 
 * @return the jSON array
 */
private JSONArray buildChildren(MetaTreeNode focusNode, int page, int levels) {
    int children = 0;
    JSONArray childrenArray = new JSONArray();

    ChildIterator itr = focusNode.getChildren();
    List<String> childrenCuis = new ArrayList<String>();
    while (itr.hasNext() && children < (MAX_CHILDREN * page) && levels > 0) {
        MetaTreeNode child = itr.next();
        childrenCuis.add(child.getCui());

        JSONObject obj = buildNode(child);
        try {
            obj.put("CHILDREN_NODES", buildChildrenNodes(child, levels - 1));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        childrenArray.put(obj);
        children++;
    }

    if (children >= MAX_CHILDREN) {
        childrenArray.put(buildMoreChildrenNode(focusNode.getCui(), focusNode.getSab(), childrenCuis));
    }

    return childrenArray;
}

From source file:org.LexGrid.lexevs.metabrowser.helper.ChildPagingJsonConverter.java

/**
 * Walk tree from root.// w  w w  .  ja  v a2  s. c  o  m
 * 
 * @param node the node
 * 
 * @return the jSON object
 */
private JSONObject walkTreeFromRoot(MetaTreeNode node, boolean isRoot) {
    int childLimit;
    if (isRoot) {
        childLimit = Integer.MAX_VALUE;
    } else {
        childLimit = MAX_CHILDREN;
    }
    JSONObject nodeObject = new JSONObject();

    try {
        nodeObject = buildNode(node);

        JSONArray childrenArray = new JSONArray();

        if (node.getPathToRootChilden() != null) {
            List<String> childrenCuis = new ArrayList<String>();

            int children = 0;
            for (MetaTreeNode child : node.getPathToRootChilden()) {
                children++;
                childrenCuis.add(child.getCui());
                childrenArray.put(walkTreeFromRoot(child, false));
            }

            ChildIterator itr = node.getChildren();
            if (itr != null) {
                while (itr.hasNext() && children < childLimit) {
                    MetaTreeNode child = itr.next();
                    if (!knownChildrenContainsCode(node.getPathToRootChilden(), child.getCui())) {
                        childrenArray.put(walkTreeFromRoot(child, false));
                        childrenCuis.add(child.getCui());
                        children++;
                    }
                }
            }

            if (children >= childLimit) {
                childrenArray.put(buildMoreChildrenNode(node.getCui(), node.getSab(), childrenCuis));
            }
        }
        nodeObject.put(CHILDREN_NODES, childrenArray);

    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

    return nodeObject;
}

From source file:org.LexGrid.lexevs.metabrowser.helper.ChildPagingJsonConverter.java

/**
 * Builds the node.// w  w w. j a va 2  s . c  o  m
 * 
 * @param node the node
 * 
 * @return the jSON object
 */
private JSONObject buildNode(MetaTreeNode node) {
    JSONObject nodeObject = new JSONObject();

    try {
        nodeObject.put(ONTOLOGY_NODE_CHILD_COUNT, expandableStatusToInt(node.getExpandedState()));
        nodeObject.put(ONTOLOGY_NODE_ID, node.getCui());
        nodeObject.put(ONTOLOGY_NODE_NAME, node.getName());

        JSONArray childrenArray = new JSONArray();
        nodeObject.put(CHILDREN_NODES, childrenArray);

        return nodeObject;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.LexGrid.lexevs.metabrowser.helper.ChildPagingJsonConverter.java

/**
 * Builds the more children node./*from ww w . j a  v  a2s.  com*/
 * 
 * @param parent the parent
 * 
 * @return the jSON object
 */
private JSONObject buildMoreChildrenNode(String parentCui, String sab, List<String> childrenCuis) {
    JSONObject nodeObject = new JSONObject();

    try {
        nodeObject.put(ONTOLOGY_NODE_CHILD_COUNT, 1);
        nodeObject.put(ONTOLOGY_NODE_ID,
                parentCui + "|" + sab + "|" + buildChildrenCuisString(childrenCuis) + "|" + 0);
        nodeObject.put(ONTOLOGY_NODE_NAME, MORE_CHILDREN_INDICATOR);
        nodeObject.put(PAGE, 1);

        JSONArray childrenArray = new JSONArray();
        nodeObject.put(CHILDREN_NODES, childrenArray);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return nodeObject;
}

From source file:com.adintellig.UDFJson.java

private Object extract_json_withkey(Object json, String path) throws JSONException {
    if (json.getClass() == org.json.JSONArray.class) {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < ((JSONArray) json).length(); i++) {
            Object josn_elem = ((JSONArray) json).get(i);
            try {
                Object json_obj = ((JSONObject) josn_elem).get(path);
                if (json_obj.getClass() == org.json.JSONArray.class) {
                    for (int j = 0; j < ((JSONArray) json_obj).length(); j++) {
                        jsonArray.put(((JSONArray) json_obj).get(j));
                    }//from   ww w.  j  av a 2 s. c  om
                } else {
                    jsonArray.put(json_obj);
                }
            } catch (Exception e) {
                continue;
            }
        }
        return (jsonArray.length() == 0) ? null : jsonArray;
    } else {
        return ((JSONObject) json).get(path);
    }
}

From source file:ch.ethz.inf.vs.android.g54.a4.util.SnapshotCache.java

private static JSONArray readingsToJson(List<WifiReading> readings) throws JSONException {
    JSONArray rs = new JSONArray();
    for (WifiReading reading : readings) {
        JSONObject ap = new JSONObject();
        ap.put("mac", reading.mac);
        ap.put("ssid", reading.ssid);
        ap.put("signal", reading.signal);
        rs.put(ap);/*  ww  w . j  a v  a  2  s  .  c om*/
    }
    return rs;
}