Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:org.qi4j.library.eventsourcing.application.source.helper.ApplicationEventParameters.java

/**
 * Get the named parameter from an event.
 *
 * @param event event with parameters//from www  .  j a va2s  .c  o  m
 * @param name  name of parameter
 * @return the parameter with the given name or null
 */
public static String getParameter(ApplicationEvent event, String name) {
    String parametersJson = event.parameters().get();
    try {
        JSONObject jsonObject = new JSONObject(parametersJson);
        return jsonObject.get(name).toString();
    } catch (JSONException e) {
        return null;
    }
}

From source file:org.qi4j.library.eventsourcing.application.source.helper.ApplicationEventParameters.java

/**
 * Get parameter with given index./*from  w w w . j a v a2s . c  om*/
 *
 * @param event event with parameters
 * @param idx   index of parameter
 * @return the parameter with the given index or null
 * @throws org.json.JSONException
 */
public static String getParameter(ApplicationEvent event, int idx) {
    try {
        String parametersJson = event.parameters().get();
        JSONObject jsonObject = new JSONObject(parametersJson);
        return jsonObject.get("param" + idx).toString();
    } catch (JSONException e) {
        return null;
    }
}

From source file:edu.stanford.junction.test.multiconnect.Receiver.java

@Override
public void onMessageReceived(MessageHeader header, JSONObject inbound) {
    System.out.println(mName + " :: " + inbound);

    try {/*  w w w. j  a v a2  s.c  om*/
        JSONObject msg = new JSONObject();
        msg.put("thanksFor", inbound.get("tic"));
        //header.getReplyTarget().sendMessage(msg);
        sendMessageToActor(header.getSender(), msg);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.soomla.store.domain.virtualGoods.EquippableVG.java

/**
 * see parent//from   w w  w  . j av  a  2s  .c  om
 */
@Override
public JSONObject toJSONObject() {
    JSONObject parentJsonObject = super.toJSONObject();
    JSONObject jsonObject = new JSONObject();
    try {
        Iterator<?> keys = parentJsonObject.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            jsonObject.put(key, parentJsonObject.get(key));
        }

        jsonObject.put(JSONConsts.EQUIPPABLE_EQUIPPING, mEquippingModel.toString());
    } catch (JSONException e) {
        StoreUtils.LogError(TAG, "An error occurred while generating JSON object.");
    }

    return jsonObject;
}

From source file:org.archive.porky.JSON.java

/**
 * Convert JSON object into a Pig object, recursively convert
 * children as well.//from  ww  w .j  a  v a 2 s  . c o m
 */
public static Object fromJSON(Object o) throws IOException, JSONException {
    if (o instanceof String || o instanceof Long || o instanceof Double || o instanceof Integer) {
        return o;
    } else if (JSONObject.NULL.equals(o)) {
        return null;
    } else if (o instanceof JSONObject) {
        JSONObject json = (JSONObject) o;

        Map<String, Object> map = new HashMap<String, Object>(json.length());

        // If getNames() returns null, then it's  an empty JSON object.
        String[] names = JSONObject.getNames(json);

        if (names == null)
            return map;

        for (String key : JSONObject.getNames(json)) {
            Object value = json.get(key);

            // Recurse the value
            map.put(key, fromJSON(value));
        }

        // Now, check to see if the map keys match the formula for
        // a Tuple, that is if they are: "$0", "$1", "$2", ...

        // First, peek to see if there is a "$0" key, if so, then 
        // start moving the map entries into a Tuple.
        if (map.containsKey("$0")) {
            Tuple tuple = TupleFactory.getInstance().newTuple(map.size());

            for (int i = 0; i < map.size(); i++) {
                // If any of the expected $N keys is not found, give
                // up and return the map.
                if (!map.containsKey("$" + i))
                    return map;

                tuple.set(i, map.get("$" + i));
            }

            return tuple;
        }

        return map;
    } else if (o instanceof JSONArray) {
        JSONArray json = (JSONArray) o;

        List<Tuple> tuples = new ArrayList<Tuple>(json.length());

        for (int i = 0; i < json.length(); i++) {
            tuples.add(TupleFactory.getInstance().newTuple(fromJSON(json.get(i))));
        }

        DataBag bag = BagFactory.getInstance().newDefaultBag(tuples);

        return bag;
    } else if (o instanceof Boolean) {
        // Since Pig doesn't have a true boolean data type, we map it to
        // String values "true" and "false".
        if (((Boolean) o).booleanValue()) {
            return "true";
        }
        return "false";
    } else {
        // FIXME: What to do here?
        throw new IOException("Unknown data-type serializing from JSON: " + o);
    }
}

From source file:org.jabsorb.ng.serializer.impl.MapSerializer.java

@Override
public ObjectMatch tryUnmarshall(final SerializerState state, final Class<?> clazz, final Object o)
        throws UnmarshallException {

    final JSONObject jso = (JSONObject) o;
    String java_class;

    // Hint presence
    try {//  w ww. j av  a  2s  .  com
        java_class = jso.getString("javaClass");
    } catch (final JSONException e) {
        throw new UnmarshallException("Could not read javaClass", e);
    }
    if (java_class == null) {
        throw new UnmarshallException("no type hint");
    }

    // Class compatibility check
    if (!classNameCheck(java_class)) {
        // FIXME: previous version also handled Properties
        throw new UnmarshallException("not a Map");
    }

    // JSON Format check
    JSONObject jsonmap;
    try {
        jsonmap = jso.getJSONObject("map");
    } catch (final JSONException e) {
        throw new UnmarshallException("Could not read map: " + e.getMessage(), e);
    }
    if (jsonmap == null) {
        throw new UnmarshallException("map missing");
    }

    // Content check
    final ObjectMatch m = new ObjectMatch(-1);
    state.setSerialized(o, m);

    final Iterator<?> i = jsonmap.keys();
    String key = null;
    try {
        while (i.hasNext()) {
            key = (String) i.next();
            m.setMismatch(ser.tryUnmarshall(state, null, jsonmap.get(key)).max(m).getMismatch());
        }
    } catch (final UnmarshallException e) {
        throw new UnmarshallException("key " + key + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new UnmarshallException("key " + key + " " + e.getMessage(), e);
    }
    return m;
}

From source file:org.jabsorb.ng.serializer.impl.MapSerializer.java

@Override
public Object unmarshall(final SerializerState state, final Class<?> clazz, final Object o)
        throws UnmarshallException {

    final JSONObject jso = (JSONObject) o;
    String java_class;

    // Hint check
    try {/*ww  w  .  ja  v  a 2  s .  c o  m*/
        java_class = jso.getString("javaClass");
    } catch (final JSONException e) {
        throw new UnmarshallException("Could not read javaClass", e);
    }

    if (java_class == null) {
        throw new UnmarshallException("no type hint");
    }

    // Create the map
    final Map<Object, Object> abmap;
    if (java_class.equals("java.util.Map") || java_class.equals("java.util.AbstractMap")
            || java_class.equals("java.util.HashMap")) {
        abmap = new HashMap<Object, Object>();
    } else if (java_class.equals("java.util.TreeMap")) {
        abmap = new TreeMap<Object, Object>();
    } else if (java_class.equals("java.util.LinkedHashMap")) {
        abmap = new LinkedHashMap<Object, Object>();
    } else if (java_class.equals("java.util.Properties")) {
        abmap = new Properties();
    } else {
        throw new UnmarshallException("not a Map");
    }

    // Parse the JSON map
    JSONObject jsonmap;
    try {
        jsonmap = jso.getJSONObject("map");
    } catch (final JSONException e) {
        throw new UnmarshallException("Could not read map: " + e.getMessage(), e);
    }
    if (jsonmap == null) {
        throw new UnmarshallException("map missing");
    }

    state.setSerialized(o, abmap);

    final Iterator<?> i = jsonmap.keys();
    String key = null;
    try {
        while (i.hasNext()) {
            key = (String) i.next();
            abmap.put(key, ser.unmarshall(state, null, jsonmap.get(key)));
        }
    } catch (final UnmarshallException e) {
        throw new UnmarshallException("key " + key + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new UnmarshallException("key " + key + " " + e.getMessage(), e);
    }

    return abmap;
}

From source file:com.facebook.share.internal.ShareInternalUtility.java

public static JSONObject removeNamespacesFromOGJsonObject(JSONObject jsonObject, boolean requireNamespace) {
    if (jsonObject == null) {
        return null;
    }//  w  ww . j a v a2 s .com

    try {
        JSONObject newJsonObject = new JSONObject();
        JSONObject data = new JSONObject();
        JSONArray names = jsonObject.names();
        for (int i = 0; i < names.length(); ++i) {
            String key = names.getString(i);
            Object value = null;
            value = jsonObject.get(key);
            if (value instanceof JSONObject) {
                value = removeNamespacesFromOGJsonObject((JSONObject) value, true);
            } else if (value instanceof JSONArray) {
                value = removeNamespacesFromOGJsonArray((JSONArray) value, true);
            }

            Pair<String, String> fieldNameAndNamespace = getFieldNameAndNamespaceFromFullName(key);
            String namespace = fieldNameAndNamespace.first;
            String fieldName = fieldNameAndNamespace.second;

            if (requireNamespace) {
                if (namespace != null && namespace.equals("fbsdk")) {
                    newJsonObject.put(key, value);
                } else if (namespace == null || namespace.equals("og")) {
                    newJsonObject.put(fieldName, value);
                } else {
                    data.put(fieldName, value);
                }
            } else if (namespace != null && namespace.equals("fb")) {
                newJsonObject.put(key, value);
            } else {
                newJsonObject.put(fieldName, value);
            }
        }

        if (data.length() > 0) {
            newJsonObject.put("data", data);
        }

        return newJsonObject;
    } catch (JSONException e) {
        throw new FacebookException("Failed to create json object from share content");
    }
}

From source file:org.aksw.simba.cetus.fox.FoxBasedTypeSearcher.java

protected void parseType(JSONObject entity, TypedNamedEntity ne, List<ExtendedTypedNamedEntity> surfaceForms)
        throws Exception {
    try {/*from   w w w.  ja  v  a 2  s.c  o  m*/

        if (entity != null && entity.has("means") && entity.has("beginIndex") && entity.has("ann:body")) {

            String uri = entity.getString("means");
            String body = entity.getString("ann:body");
            Object begin = entity.get("beginIndex");
            Object typeObject = entity.get("@type");
            String types[];
            if (typeObject instanceof JSONArray) {
                JSONArray typeArray = (JSONArray) typeObject;
                types = new String[typeArray.length()];
                for (int i = 0; i < types.length; ++i) {
                    types[i] = typeArray.getString(i);
                }
            } else {
                types = new String[] { typeObject.toString() };
            }
            URLDecoder.decode(uri, "UTF-8");
            if (begin instanceof JSONArray) {
                // for all indices
                for (int i = 0; i < ((JSONArray) begin).length(); ++i) {
                    addTypeIfOverlapping(ne, Integer.valueOf(((JSONArray) begin).getString(i)), body.length(),
                            types);
                }
            } else if (begin instanceof String) {
                addTypeIfOverlapping(ne, Integer.valueOf((String) begin), body.length(), types);
            } else if (LOGGER.isDebugEnabled())
                LOGGER.debug("Couldn't find index");
        }
    } catch (Exception e) {
        LOGGER.error("Got an Exception while parsing the response of FOX.", e);
        throw new Exception("Got an Exception while parsing the response of FOX.", e);
    }
}

From source file:org.everit.json.schema.ObjectSchema.java

private void testProperties(final JSONObject subject) {
    if (propertySchemas != null) {
        for (Entry<String, Schema> entry : propertySchemas.entrySet()) {
            String key = entry.getKey();
            if (subject.has(key)) {
                entry.getValue().validate(subject.get(key));
            }/*  w  w  w .  ja v  a 2 s .c  o  m*/
        }
    }
}