Example usage for org.json JSONObject opt

List of usage examples for org.json JSONObject opt

Introduction

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

Prototype

public Object opt(String key) 

Source Link

Document

Get an optional value associated with a key.

Usage

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;/*ww w  .j a v a2s .c o  m*/
    }

    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.jandroid2cloud.connection.ChannelHandler.java

@Override
public void message(String rawMsg) {
    logger.debug("Received message from server:" + rawMsg);

    try {//w  w w.ja  v a 2 s  .co  m
        JSONObject jsonMessage = new JSONObject(new JSONTokener(rawMsg));
        JSONObject links = (JSONObject) jsonMessage.opt("links");
        if (links == null) {
            JSONObject link = jsonMessage.optJSONObject("link");
            handleLink(link);
        } else {
            Iterator it = links.keys();
            while (it.hasNext()) {
                String s = (String) it.next();
                if (s != null && !s.isEmpty()) {
                    JSONObject o = links.getJSONObject(s);
                    handleLink(o);
                }
            }
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("links", rawMsg);
        String response = oauth.makeRequest("http://" + config.getHost() + "/markread", Verb.POST, params);
        logger.debug("Marked message as read");
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (NetworkException e) {
        logger.error(NotificationAppender.MARKER, "Could not mark links as read.\n"
                + "You will not receive more links until that is done.\n" + "See log for details", e);
    }
}

From source file:sandeep.kb.android.remote.android.AndroidWebDriver.java

private Object convertJsonToJavaObject(final Object toConvert) {
    try {/*from   w w  w  .j  ava 2 s . c  o m*/
        if (toConvert == null || toConvert.equals(null) || "undefined".equals(toConvert)
                || "null".equals(toConvert)) {
            return null;
        } else if (toConvert instanceof Boolean) {
            return toConvert;
        } else if (toConvert instanceof Double || toConvert instanceof Float) {
            return Double.valueOf(String.valueOf(toConvert));
        } else if (toConvert instanceof Integer || toConvert instanceof Long) {
            return Long.valueOf(String.valueOf(toConvert));
        } else if (toConvert instanceof JSONArray) { // List
            return convertJsonArrayToList((JSONArray) toConvert);
        } else if (toConvert instanceof JSONObject) { // Map or WebElment
            JSONObject map = (JSONObject) toConvert;
            if (map.opt(ELEMENT_KEY) != null) { // WebElement
                return getOrCreateWebElement((String) map.get(ELEMENT_KEY));
            } else if (map.opt(WINDOW_KEY) != null) { // DomWindow
                return new DomWindow((String) map.get(WINDOW_KEY));
            } else { // Map
                return convertJsonObjectToMap(map);
            }
        } else {
            return toConvert.toString();
        }
    } catch (JSONException e) {
        throw new RuntimeException("Failed to parse JavaScript result: " + toConvert.toString(), e);
    }
}

From source file:net.geco.model.iojson.PersistentStore.java

public void importRunnersData(JSONStore store, Registry registry, Factory factory) throws JSONException {
    final int I_RUNNER = 0;
    final int I_ECARD = 1;
    final int I_RESULT = 2;
    JSONArray runnersData = store.getJSONArray(K.RUNNERS_DATA);
    for (int i = 0; i < runnersData.length(); i++) {
        JSONArray runnerTuple = runnersData.getJSONArray(i);

        JSONObject c = runnerTuple.getJSONObject(I_RUNNER);
        Runner runner = factory.createRunner();
        runner.setStartId(c.getInt(K.START_ID));
        runner.setFirstname(c.getString(K.FIRST));
        runner.setLastname(c.getString(K.LAST));
        runner.setEcard(c.getString(K.ECARD));
        runner.setClub(store.retrieve(c.getInt(K.CLUB), Club.class));
        runner.setCategory(store.retrieve(c.getInt(K.CAT), Category.class));
        runner.setCourse(store.retrieve(c.getInt(K.COURSE), Course.class));
        runner.setRegisteredStarttime(new Date(c.getLong(K.START)));
        runner.setArchiveId((Integer) c.opt(K.ARK));
        runner.setRentedEcard(c.optBoolean(K.RENT));
        runner.setNC(c.optBoolean(K.NC));
        registry.addRunner(runner);//  w  w  w . j a  v a  2s.  co  m

        JSONObject d = runnerTuple.getJSONObject(I_ECARD);
        RunnerRaceData raceData = factory.createRunnerRaceData();
        raceData.setStarttime(new Date(d.getLong(K.START)));
        raceData.setFinishtime(new Date(d.getLong(K.FINISH)));
        raceData.setControltime(new Date(d.getLong(K.CHECK)));
        raceData.setReadtime(new Date(d.getLong(K.READ)));
        JSONArray p = d.getJSONArray(K.PUNCHES);
        Punch[] punches = new Punch[p.length() / 2];
        for (int j = 0; j < punches.length; j++) {
            punches[j] = factory.createPunch();
            punches[j].setCode(p.getInt(2 * j));
            punches[j].setTime(new Date(p.getLong(2 * j + 1)));
        }
        raceData.setPunches(punches);
        raceData.setRunner(runner);
        registry.addRunnerData(raceData);

        JSONObject r = runnerTuple.getJSONObject(I_RESULT);
        TraceData traceData = factory.createTraceData();
        traceData.setNbMPs(r.getInt(K.MPS));
        traceData.setNbExtraneous(r.optInt(K.EXTRA)); // MIGR v2.x -> v2.3
        JSONArray t = r.getJSONArray(K.TRACE);
        Trace[] trace = new Trace[t.length() / 2];
        for (int j = 0; j < trace.length; j++) {
            trace[j] = factory.createTrace(t.getString(2 * j), new Date(t.getLong(2 * j + 1)));
        }
        if (r.has(K.SECTION_DATA)) {
            SectionTraceData sectionData = (SectionTraceData) traceData;
            JSONArray sections = r.getJSONArray(K.SECTION_DATA);
            for (int j = 0; j < sections.length(); j++) {
                JSONArray section = sections.getJSONArray(j);
                sectionData.putSectionAt(store.retrieve(section.getInt(0), Section.class), section.getInt(1));
            }
        }
        JSONArray neut = r.getJSONArray(K.NEUTRALIZED);
        for (int j = 0; j < neut.length(); j++) {
            trace[neut.getInt(j)].setNeutralized(true);
        }
        traceData.setTrace(trace);
        raceData.setTraceData(traceData);

        RunnerResult result = factory.createRunnerResult();
        result.setRaceTime(r.optLong(K.RACE_TIME, TimeManager.NO_TIME_l)); // MIGR v2.x -> v2.2
        result.setResultTime(r.getLong(K.TIME));
        result.setStatus(Status.valueOf(r.getString(K.STATUS)));
        result.setTimePenalty(r.getLong(K.PENALTY));
        result.setManualTimePenalty(r.optLong(K.MANUAL_PENALTY, 0)); // MIGR v2.x -> v2.3
        raceData.setResult(result);
    }
}

From source file:com.futureplatforms.kirin.internal.attic.ProxyGenerator.java

private Object handleGetter(final JSONObject obj, Class<?> returnType, String propertyName) throws Exception {
    Object retValue = obj.opt(propertyName);

    if (retValue instanceof JSONObject) {
        if (returnType.isInterface()) {
            return javascriptProxyForResponse((JSONObject) retValue, returnType);
        } else if (!JSONObject.class.equals(returnType)) {
            throw new Exception("Trying to cast a JSONObject to a " + returnType.getName());
        }//from ww  w .  jav a2s  .  co  m
    }
    return retValue;
}

From source file:fr.arnaudguyon.xmltojsonlib.JsonToXml.java

private void prepareObject(Node node, JSONObject json) {
    Iterator<String> keyterator = json.keys();
    while (keyterator.hasNext()) {
        String key = keyterator.next();
        Object object = json.opt(key);
        if (object != null) {
            if (object instanceof JSONObject) {
                JSONObject subObject = (JSONObject) object;
                String path = node.getPath() + "/" + key;
                Node subNode = new Node(key, path);
                node.addChild(subNode);//from  w w w. j a  v  a 2  s . co  m
                prepareObject(subNode, subObject);
            } else if (object instanceof JSONArray) {
                JSONArray array = (JSONArray) object;
                prepareArray(node, key, array);
            } else {
                String path = node.getPath() + "/" + key;
                // JSON numbers are represented either Integer or Double (IEEE 754)
                // Long may be represented in scientific notation because they are stored as Double
                // This workaround attempts to represent Long and Double objects accordingly
                String value;
                if (object instanceof Double) {
                    double d = (double) object;
                    // If it is a Long
                    if (d % 1 == 0) {
                        value = Long.toString((long) d);
                    } else {
                        // TODO: Set up number of decimal digits per attribute in the builder
                        // Set only once. Represent all double numbers up to 20 decimal digits
                        if (DECIMAL_FORMAT.getMaximumFractionDigits() == 0) {
                            DECIMAL_FORMAT.setMaximumFractionDigits(20);
                        }
                        value = DECIMAL_FORMAT.format(d);
                    }
                } else {
                    // Integer, Boolean and String are handled here
                    value = object.toString();
                }
                if (isAttribute(path)) {
                    node.addAttribute(key, value);
                } else if (isContent(path)) {
                    node.setContent(value);
                } else {
                    Node subNode = new Node(key, node.getPath());
                    subNode.setContent(value);
                    node.addChild(subNode);
                }
            }
        }
    }
}

From source file:com.sciamlab.ckan4j.exception.CKANException.java

public CKANException(JSONObject error) {
    super((error.opt("__type") != null) ? error.getString("__type") : error.toString());
    this.error = error;
}

From source file:com.textuality.lifesaver.Columns.java

public String jsonToKey(JSONObject json) {
    return json.opt(key1).toString() + "/" + json.opt(key2).toString();
}

From source file:org.chromium.ChromeStorage.java

private void set(final CordovaArgs args, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        @Override/*  ww  w  . java 2s  .c o  m*/
        public void run() {
            try {
                String namespace = args.getString(0);
                JSONObject jsonObject = (JSONObject) args.getJSONObject(1);
                JSONArray keyArray = jsonObject.names();
                JSONObject oldValues = new JSONObject();

                if (keyArray != null) {
                    List<String> keys = toStringList(keyArray);
                    JSONObject storage = getStorage(namespace);
                    for (String key : keys) {
                        Object oldValue = storage.opt(key);
                        if (oldValue != null) {
                            oldValues.put(key, oldValue);
                        }
                        storage.put(key, jsonObject.get(key));
                    }
                    setStorage(namespace, storage);
                }
                callbackContext.success(oldValues);
            } catch (Exception e) {
                Log.e(LOG_TAG, "Could not update storage", e);
                callbackContext.error("Could not update storage");
            }
        }
    });
}

From source file:org.chromium.ChromeStorage.java

private void remove(final CordovaArgs args, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        @Override//from w  ww  .jav  a2  s . com
        public void run() {
            try {
                String namespace = args.getString(0);
                JSONObject jsonObject = (JSONObject) args.optJSONObject(1);
                JSONArray jsonArray = args.optJSONArray(1);
                boolean isNull = args.isNull(1);
                List<String> keys = new ArrayList<String>();
                JSONObject oldValues = new JSONObject();

                if (jsonObject != null) {
                    keys = toStringList(jsonObject.names());
                } else if (jsonArray != null) {
                    keys = toStringList(jsonArray);
                } else if (isNull) {
                    keys = null;
                }

                if (keys != null && !keys.isEmpty()) {
                    JSONObject storage = getStorage(namespace);
                    for (String key : keys) {
                        Object oldValue = storage.opt(key);
                        if (oldValue != null) {
                            oldValues.put(key, oldValue);
                        }
                        storage.remove(key);
                    }
                    setStorage(namespace, storage);
                }
                callbackContext.success(oldValues);
            } catch (Exception e) {
                Log.e(LOG_TAG, "Could not update storage", e);
                callbackContext.error("Could not update storage");
            }
        }
    });
}