Example usage for org.json JSONObject getNames

List of usage examples for org.json JSONObject getNames

Introduction

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

Prototype

public static String[] getNames(Object object) 

Source Link

Document

Get an array of field names from an Object.

Usage

From source file:org.collectionspace.chain.csp.persistence.services.TestService.java

/**
 * Tests conversion of a JSON file to XML. This implementation does not compare the
 * resultant generated XML to an expected XML file. Instead, it converts the resultant
 * XML back into JSON, and compares that round-trip JSON to an expected JSON file.
 * //from w w  w .j  a v  a 2  s  .c om
 * @param spec
 * @param objtype
 * @param xmlfile         Name of the file containing the expected XML (not currently used)
 * @param jsonfile         Name of the file containing JSON to be converted to XML
 * @param returnedjsonfile   Name of the file containing the expected round-trip JSON, converted back from XML 
 * @throws Exception
 */
private void testJSONXML(Spec spec, String objtype, String xmlfile, String jsonfile, String returnedjsonfile)
        throws Exception {

    log.info("Converting JSON to XML for record type " + objtype);
    Record r = spec.getRecord(objtype);
    JSONObject j = getJSON(jsonfile);
    //log.info("Original JSON:\n" + j.toString());
    Map<String, Document> parts = new HashMap<String, Document>();
    Document doc = null;
    JSONObject testjson = new JSONObject();
    for (String section : r.getServicesRecordPathKeys()) {
        if (section.equals("common")) {
            String path = r.getServicesRecordPath(section);
            String[] record_path = path.split(":", 2);
            doc = XmlJsonConversion.convertToXml(r, j, section, "");
            parts.put(record_path[0], doc);
            //log.info("After JSON->XML conversion:\n" + doc.asXML());
            JSONObject repeatjson = org.collectionspace.chain.csp.persistence.services.XmlJsonConversion
                    .convertToJson(r, doc, "", "common", "", "");// this is where we
            // specify the
            // multipart
            // section
            // we are considering
            for (String name : JSONObject.getNames(repeatjson)) {
                testjson.put(name, repeatjson.get(name));
            }
            //log.info("After XML->JSON re-conversion:\n" + testjson.toString());
        }
    }
    // convert json -> xml and back to json and see if it still looks the
    // same..
    JSONObject expectedjson = getJSON(returnedjsonfile);
    boolean result = JSONUtils.checkJSONEquivOrEmptyStringKey(expectedjson, testjson);
    if (!result) {
        log.info("Original JSON:\n" + j.toString());
        log.info("After JSON->XML conversion:\n" + doc.asXML());
        log.info("After XML->JSON re-conversion:\n" + testjson.toString());
    }
    assertTrue("JSON->XML->JSON round-trip for record type: " + objtype + " doesn't match original JSON",
            result);

}

From source file:org.archive.modules.writer.WARCWriterProcessor.java

@Override
protected void fromCheckpointJson(JSONObject json) throws JSONException {
    super.fromCheckpointJson(json);

    // conditionals below are for backward compatibility with old checkpoints

    if (json.has("urlsWritten")) {
        urlsWritten.set(json.getLong("urlsWritten"));
    }//  ww w.j  av  a 2  s. c o m

    if (json.has("stats")) {
        HashMap<String, Map<String, Long>> cpStats = new HashMap<String, Map<String, Long>>();
        JSONObject jsonStats = json.getJSONObject("stats");
        if (JSONObject.getNames(jsonStats) != null) {
            for (String key1 : JSONObject.getNames(jsonStats)) {
                JSONObject jsonSubstats = jsonStats.getJSONObject(key1);
                if (!cpStats.containsKey(key1)) {
                    cpStats.put(key1, new HashMap<String, Long>());
                }
                Map<String, Long> substats = cpStats.get(key1);

                for (String key2 : JSONObject.getNames(jsonSubstats)) {
                    long value = jsonSubstats.getLong(key2);
                    substats.put(key2, value);
                }
            }
            addStats(cpStats);
        }
    }
}

From source file:fr.liglab.adele.cilia.workbench.restmonitoring.utils.http.CiliaRestHelper.java

private static Map<String, String> getComponentPropertiesFromJSON(JSONObject json) throws CiliaException {
    Map<String, String> retval = new HashMap<String, String>();
    try {//from   w w w. jav  a 2  s .  com
        JSONObject prop = (JSONObject) json.get("Properties");
        String[] keys = JSONObject.getNames(prop);
        for (String key : keys) {
            String value = prop.get(key).toString();
            retval.put(key, value);
        }
    } catch (JSONException e) {
        String message = "Error while parsing JSON message";
        throw new CiliaException(message, e);
    }

    return retval;
}

From source file:fr.liglab.adele.cilia.workbench.restmonitoring.utils.http.CiliaRestHelper.java

private static Map<String, String> getComponentInformationFromJSON(JSONObject json) throws CiliaException {
    Map<String, String> retval = new HashMap<String, String>();
    try {//from ww w .j  a va 2s  .  c om
        String[] keys = JSONObject.getNames(json);
        for (String key : keys) {
            if (!key.equalsIgnoreCase("Properties")) {
                String value = json.getString(key);
                retval.put(key, value);
            }
        }
    } catch (JSONException e) {
        String message = "Error while parsing JSON message";
        throw new CiliaException(message, e);
    }

    return retval;
}

From source file:fr.liglab.adele.cilia.workbench.restmonitoring.utils.http.CiliaRestHelper.java

/**
 * Gets the list of available statevar, and the enable status for each one.
 *///www. j  a  v  a2 s.c  o m
public static Map<String, Boolean> getStateVarList(PlatformID platformID, String chainName, String compoName)
        throws CiliaException {
    String target = "/cilia/runtime/" + chainName + "/components/" + compoName + "/setup";
    String message = HttpHelper.get(platformID, target);
    Map<String, Boolean> stateVarList = new HashMap<String, Boolean>();

    JSONObject json = string2json(message);

    for (String name : JSONObject.getNames(json)) {
        try {
            String enabled = json.getJSONObject(name).getString("Enabled");
            stateVarList.put(name, enabled.equals("true"));
        } catch (JSONException e) {
            throw new CiliaException("Can't parse message", e);
        }
    }

    return stateVarList;
}

From source file:ca.nrc.cadc.xml.JsonInputter.java

public Document input(final String json) throws JSONException {
    JSONObject rootJson = new JSONObject(json);
    List<String> keys = Arrays.asList(JSONObject.getNames(rootJson));
    List<Namespace> namespaces = new ArrayList<Namespace>();
    Namespace namespace = getNamespace(namespaces, rootJson, keys);

    String rootKey = null;//from ww w  .  ja  va 2  s .c  o  m
    List<Attribute> attributes = new ArrayList<Attribute>();
    for (String key : keys) {
        if (!key.startsWith("@xmlns")) {
            if (key.startsWith("@")) {
                String value;
                if (rootJson.isNull(key)) {
                    value = "";
                } else {
                    value = getStringValue(rootJson.get(key));
                }
                attributes.add(new Attribute(key.substring(1), value));
            } else {
                // DOM can only have one root element.
                if (rootKey != null) {
                    throw new IllegalStateException("Found multiple root entries");
                }
                rootKey = key;
            }
        }
    }

    Element rootElement = new Element(rootKey, namespace);
    for (Attribute attribute : attributes) {
        rootElement.setAttribute(attribute);
    }

    Object value = rootJson.get(rootKey);
    processObject(rootKey, value, rootElement, namespace, namespaces);

    Document document = new Document();
    document.setRootElement(rootElement);
    return document;
}

From source file:ca.nrc.cadc.xml.JsonInputter.java

private void processJSONObject(JSONObject jsonObject, Element element, List<Namespace> namespaces)
        throws JSONException {
    List<String> keys = Arrays.asList(JSONObject.getNames(jsonObject));
    Namespace namespace = getNamespace(namespaces, jsonObject, keys);
    if (namespace == null) {
        namespace = element.getNamespace();
    }// ww w .j av a2 s.c  o m

    for (String key : keys) {
        if (jsonObject.isNull(key)) {
            continue;
        }

        // attribute
        if (key.startsWith("@")) {
            Object value = jsonObject.get(key);
            element.setAttribute(new Attribute(key.substring(1), getStringValue(value)));
            continue;
        }

        // text content
        Object value = jsonObject.get(key);
        if (key.equals("$")) {
            element.setText(getStringValue(value));
            continue;
        }

        Element child = new Element(key, namespace);
        if (listElementMap.containsKey(key)) {
            final String childKey = listElementMap.get(key);
            final Object childObject = ((JSONObject) value).get("$");
            Element grandChild = new Element(childKey, namespace);

            if (childObject instanceof JSONArray) {
                processJSONArray(key, (JSONArray) childObject, child, namespace, namespaces);
            } else if (childObject instanceof JSONObject) {
                processJSONObject((JSONObject) childObject, grandChild, namespaces);
                child.addContent(grandChild);
            }
        } else if (value instanceof JSONObject) {
            processJSONObject((JSONObject) value, child, namespaces);
        }

        element.addContent(child);
    }
}

From source file:com.rapid.actions.Rapid.java

public Rapid(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {

    // call the super constructor to the set the xml version
    super();/*from  w w  w. j  a v  a  2  s .c o  m*/

    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties, except for success, error, and child actions
        if (!"successActions".equals(key) && !"errorActions".equals(key) && !"childActions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }

    // grab any successActions
    JSONArray jsonSuccessActions = jsonAction.optJSONArray("successActions");
    // if we had some
    if (jsonSuccessActions != null) {
        _successActions = Control.getActions(rapidServlet, jsonSuccessActions);
    }

    // grab any errorActions
    JSONArray jsonErrorActions = jsonAction.optJSONArray("errorActions");
    // if we had some
    if (jsonErrorActions != null) {
        _errorActions = Control.getActions(rapidServlet, jsonErrorActions);
    }

}

From source file:com.md87.charliebravo.commands.IssueCommand.java

protected void executeNewIssue(InputHandler handler, Response response, String line) throws Exception {
    final List<String> result = Downloader.getPage("http://jira.dmdirc.com/rest/api/2.0.alpha1/issue/" + line);
    final StringBuilder builder = new StringBuilder();

    for (String resline : result) {
        builder.append(resline);//from  www.j  a  v a2  s.  com
    }

    final JSONObject json = new JSONObject(builder.toString());
    final JSONObject fields = json.getJSONObject("fields");
    final Map<String, String> data = new HashMap<String, String>();
    data.put("id", json.getString("key"));

    for (String key : JSONObject.getNames(fields)) {
        JSONObject complexValue = fields.getJSONObject(key).optJSONObject("value");
        String value;

        if (complexValue == null) {
            value = fields.getJSONObject(key).optString("value", "");
        } else {
            value = complexValue.optString("name", "");
        }

        data.put(fields.getJSONObject(key).optString("name", key), value);
    }

    response.sendMessage("issue " + data.get("id") + " is \"" + data.get("summary") + "\" and is currently "
            + data.get("status").toLowerCase() + ". See http://jira.dmdirc.com/browse/" + data.get("id"));
    response.addFollowup(new IssueFollowup(data));
}

From source file:com.rapid.actions.Navigate.java

public Navigate(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // call super constructor to set xml version
    super();//from  www  .  j  a  va  2s. com
    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties (except for sessionVariables)
        if (!"sessionVariables".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }
    // get the inputs collections
    JSONArray jsonInputs = jsonAction.optJSONArray("sessionVariables");
    // check it
    if (jsonInputs == null) {
        // empty down the collection
        _sessionVariables = null;
    } else {
        // initialise the collection
        _sessionVariables = new ArrayList<SessionVariable>();
        // loop it
        for (int i = 0; i < jsonInputs.length(); i++) {
            // get this input
            JSONObject jsonInput = jsonInputs.getJSONObject(i);
            // add it to the collection
            _sessionVariables.add(new SessionVariable(jsonInput.getString("name"),
                    jsonInput.getString("itemId"), jsonInput.optString("field")));
        }
    }
}