Example usage for org.json JSONObject keys

List of usage examples for org.json JSONObject keys

Introduction

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

Prototype

public Iterator keys() 

Source Link

Document

Get an enumeration of the keys of the JSONObject.

Usage

From source file:es.upm.dit.xsdinferencer.extraction.extractorImpl.JSONTypesExtractorImpl.java

/**
 * This method adds additional quotes to any String value inside a JSON. 
 * This helps to distinguish whether values come from strings or other 
 * primitive types when the JSON is converted to XML. 
 * @param jsonRoot/*from www. j ava  2 s . c  om*/
 */
private void quoteStringsAtJSON(Object jsonRoot) {
    if (jsonRoot instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) jsonRoot;
        ImmutableSet<String> jsonObjectKeys = ImmutableSet.copyOf(jsonObject.keys());
        for (String key : jsonObjectKeys) {
            Object value = jsonObject.get(key);
            if (value instanceof String) {
                String valueStr = (String) value;
                jsonObject.put(key, "\"" + valueStr + "\"");
            } else if (value instanceof JSONObject || value instanceof JSONArray) {
                quoteStringsAtJSON(value);
            }
        }
    } else if (jsonRoot instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) jsonRoot;
        for (int i = 0; i < jsonArray.length(); i++) {
            Object value = jsonArray.get(i);
            if (value instanceof String) {
                String valueStr = (String) value;
                jsonArray.put(i, "\"" + valueStr + "\"");
            } else if (value instanceof JSONObject || value instanceof JSONArray) {
                quoteStringsAtJSON(value);
            }
        }
    } else {
        return;
    }
}

From source file:com.nextgis.maplib.map.VectorLayer.java

public String createFromGeoJSON(JSONObject geoJSONObject) {
    try {//from w w  w.java 2  s.c om
        //check crs
        boolean isWGS84 = true; //if no crs tag - WGS84 CRS
        if (geoJSONObject.has(GEOJSON_CRS)) {
            JSONObject crsJSONObject = geoJSONObject.getJSONObject(GEOJSON_CRS);
            //the link is unsupported yet.
            if (!crsJSONObject.getString(GEOJSON_TYPE).equals(GEOJSON_NAME)) {
                return mContext.getString(R.string.error_crs_unsuported);
            }
            JSONObject crsPropertiesJSONObject = crsJSONObject.getJSONObject(GEOJSON_PROPERTIES);
            String crsName = crsPropertiesJSONObject.getString(GEOJSON_NAME);
            if (crsName.equals("urn:ogc:def:crs:OGC:1.3:CRS84")) { // WGS84
                isWGS84 = true;
            } else if (crsName.equals("urn:ogc:def:crs:EPSG::3857") || crsName.equals("EPSG:3857")) { //Web Mercator
                isWGS84 = false;
            } else {
                return mContext.getString(R.string.error_crs_unsuported);
            }
        }

        //load contents to memory and reproject if needed
        JSONArray geoJSONFeatures = geoJSONObject.getJSONArray(GEOJSON_TYPE_FEATURES);
        if (0 == geoJSONFeatures.length()) {
            return mContext.getString(R.string.error_empty_dataset);
        }

        List<Feature> features = new ArrayList<>();
        List<Pair<String, Integer>> fields = new ArrayList<>();

        int geometryType = GTNone;
        for (int i = 0; i < geoJSONFeatures.length(); i++) {
            JSONObject jsonFeature = geoJSONFeatures.getJSONObject(i);
            //get geometry
            JSONObject jsonGeometry = jsonFeature.getJSONObject(GEOJSON_GEOMETRY);
            GeoGeometry geometry = GeoGeometry.fromJson(jsonGeometry);
            if (geometryType == GTNone) {
                geometryType = geometry.getType();
            } else if (!Geo.isGeometryTypeSame(geometryType, geometry.getType())) {
                //skip different geometry type
                continue;
            }

            //reproject if needed
            if (isWGS84) {
                geometry.setCRS(CRS_WGS84);
                geometry.project(CRS_WEB_MERCATOR);
            } else {
                geometry.setCRS(CRS_WEB_MERCATOR);
            }

            int nId = i;
            if (jsonFeature.has(GEOJSON_ID))
                nId = jsonFeature.getInt(GEOJSON_ID);
            Feature feature = new Feature(nId, fields); // ID == i
            feature.setGeometry(geometry);

            //normalize attributes
            JSONObject jsonAttributes = jsonFeature.getJSONObject(GEOJSON_PROPERTIES);
            Iterator<String> iter = jsonAttributes.keys();
            while (iter.hasNext()) {
                String key = iter.next();
                Object value = jsonAttributes.get(key);
                int nType = NOT_FOUND;
                //check type
                if (value instanceof Integer || value instanceof Long) {
                    nType = FTInteger;
                } else if (value instanceof Double || value instanceof Float) {
                    nType = FTReal;
                } else if (value instanceof Date) {
                    nType = FTDateTime;
                } else if (value instanceof String) {
                    nType = FTString;
                } else if (value instanceof JSONObject) {
                    nType = NOT_FOUND;
                    //the some list - need to check it type FTIntegerList, FTRealList, FTStringList
                }

                if (nType != NOT_FOUND) {
                    int fieldIndex = NOT_FOUND;
                    for (int j = 0; j < fields.size(); j++) {
                        if (fields.get(j).first.equals(key)) {
                            fieldIndex = j;
                        }
                    }
                    if (fieldIndex == NOT_FOUND) { //add new field
                        Pair<String, Integer> fieldKey = Pair.create(key, nType);
                        fieldIndex = fields.size();
                        fields.add(fieldKey);
                    }
                    feature.setFieldValue(fieldIndex, value);
                }
            }
            features.add(feature);
        }

        String tableCreate = "CREATE TABLE IF NOT EXISTS " + mPath.getName() + " ( " + //table name is the same as the folder of the layer
                "_ID INTEGER PRIMARY KEY, " + "GEOM BLOB";
        for (int i = 0; i < fields.size(); ++i) {
            Pair<String, Integer> field = fields.get(i);

            tableCreate += ", " + field.first + " ";
            switch (field.second) {
            case FTString:
                tableCreate += "TEXT";
                break;
            case FTInteger:
                tableCreate += "INTEGER";
                break;
            case FTReal:
                tableCreate += "REAL";
                break;
            case FTDateTime:
                tableCreate += "TIMESTAMP";
                break;
            }
        }
        tableCreate += " );";

        GeoEnvelope extents = new GeoEnvelope();
        for (Feature feature : features) {
            //update bbox
            extents.merge(feature.getGeometry().getEnvelope());
        }

        //1. create table and populate with values
        MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
        SQLiteDatabase db = map.getDatabase(true);
        db.execSQL(tableCreate);
        for (Feature feature : features) {
            ContentValues values = new ContentValues();
            values.put("_ID", feature.getId());
            try {
                values.put("GEOM", feature.getGeometry().toBlob());
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < fields.size(); ++i) {
                if (!feature.isValuePresent(i))
                    continue;
                switch (fields.get(i).second) {
                case FTString:
                    values.put(fields.get(i).first, feature.getFieldValueAsString(i));
                    break;
                case FTInteger:
                    values.put(fields.get(i).first, (int) feature.getFieldValue(i));
                    break;
                case FTReal:
                    values.put(fields.get(i).first, (double) feature.getFieldValue(i));
                    break;
                case FTDateTime:
                    values.put(fields.get(i).first, feature.getFieldValueAsString(i));
                    break;
                }
            }
            db.insert(mPath.getName(), "", values);
        }

        //2. save the layer properties to config.json
        mGeometryType = geometryType;
        mExtents = extents;
        mIsInitialized = true;
        setDefaultRenderer();

        save();

        //3. fill the geometry and labels array
        mVectorCacheItems = new ArrayList<>();
        for (Feature feature : features) {
            mVectorCacheItems.add(new VectorCacheItem(feature.getGeometry(), feature.getId()));
        }

        if (null != mParent) { //notify the load is over
            LayerGroup layerGroup = (LayerGroup) mParent;
            layerGroup.onLayerChanged(this);
        }

        return "";
    } catch (JSONException e) {
        e.printStackTrace();
        return e.getLocalizedMessage();
    }
}

From source file:com.jsonstore.api.JSONStoreFindOptions.java

/**
 * @exclude Used internally/*from   w  w  w.jav  a 2 s  .  c  o  m*/
 */
public JSONStoreFindOptions(JSONObject options) throws JSONException, JSONStoreInvalidSortObjectException {

    filter = new HashMap<String, Boolean>();
    sort = new LinkedHashMap<String, SortDirection>();

    String limitStr = options.optString(JSONStoreFindOptions.OPTION_LIMIT, null);
    if (limitStr != null) {
        Integer limitParse = Integer.parseInt(limitStr);
        setLimit(limitParse);
    }

    String offsetStr = options.optString(JSONStoreFindOptions.OPTION_OFFSET, null);
    if (offsetStr != null) {
        Integer offsetParse = Integer.parseInt(offsetStr);
        setOffset(offsetParse);
    }

    JSONArray sortArray = options.optJSONArray(JSONStoreFindOptions.OPTION_SORT_ARRAY);
    if (sortArray != null) {
        for (int idx = 0; idx < sortArray.length(); idx++) {
            JSONObject sortObject = sortArray.getJSONObject(idx);

            Iterator<String> keys = sortObject.keys();
            String key = keys.next();

            if (keys.hasNext()) {
                throw new JSONStoreInvalidSortObjectException(
                        "One of the sort objects in the sort array has more than one field.");
            }

            //Parse the direction of the sort for this search field:
            String sortDirectionStr = sortObject.getString(key);
            if (sortDirectionStr.equalsIgnoreCase(DatabaseConstants.ASCENDING)) {
                sortBySearchFieldAscending(key);
            } else if (sortDirectionStr.equalsIgnoreCase(DatabaseConstants.DESCENDING)) {
                sortBySearchFieldDescending(key);
            } else {
                throw new JSONStoreInvalidSortObjectException(
                        "Invalid sorting direction (ascending or descending) specified.");
            }
        }

    }

    JSONArray filterParse = options.optJSONArray(JSONStoreFindOptions.OPTION_FILTER);
    if (filterParse != null) {
        for (int idx = 0; idx < filterParse.length(); idx++) {
            addSearchFilter(filterParse.getString(idx));
        }
    }
}

From source file:com.facebook.share.ShareApi.java

private static void putImageInBundleWithArrayFormat(Bundle parameters, int index, JSONObject image)
        throws JSONException {
    Iterator<String> keys = image.keys();
    while (keys.hasNext()) {
        String property = keys.next();
        String key = String.format(Locale.ROOT, "image[%d][%s]", index, property);
        parameters.putString(key, image.get(property).toString());
    }/*from   w w  w .j  ava 2  s.c o  m*/
}

From source file:com.whizzosoftware.hobson.scheduler.ical.ICalTask.java

private void addActionRef(JSONObject json) {
    HobsonActionRef ref = new HobsonActionRef(json.getString("pluginId"), json.getString("actionId"),
            json.getString("name"));
    if (json.has("properties")) {
        JSONObject propJson = json.getJSONObject("properties");
        Iterator it = propJson.keys();
        while (it.hasNext()) {
            String key = (String) it.next();
            ref.addProperty(key, propJson.get(key));
        }/*w  w  w. ja  v a2  s  .  co m*/
    }
    actions.add(ref);
}

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;
                    }//from   ww w . j a  va2  s  . com
                    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.protorabbit.Config.java

@SuppressWarnings("unchecked")
private void registerTemplates(ITemplate temp, JSONObject t, String baseURI) {

    try {//from  w w w. jav a  2  s.  c  o  m

        if (t.has("timeout")) {
            long templateTimeout = t.getLong("timeout");
            temp.setTimeout(templateTimeout);
        }

        boolean tgzip = false;

        if (!devMode) {
            tgzip = gzip;
        }

        if (t.has("gzip")) {
            tgzip = t.getBoolean("gzip");
            temp.setGzipStyles(tgzip);
            temp.setGzipScripts(tgzip);
            temp.setGzipTemplate(tgzip);
        }

        if (t.has("uniqueURL")) {
            Boolean unique = t.getBoolean("uniqueURL");
            temp.setUniqueURL(unique);
        }

        // template overrides default combineResources
        if (t.has("combineResources")) {
            boolean combineResources = t.getBoolean("combineResources");
            temp.setCombineResources(combineResources);
            temp.setCombineScripts(combineResources);
            temp.setCombineStyles(combineResources);
        }

        if (t.has("template")) {
            String turi = t.getString("template");
            ResourceURI templateURI = new ResourceURI(turi, baseURI, ResourceURI.TEMPLATE);
            temp.setTemplateURI(templateURI);
        }

        if (t.has("namespace")) {
            temp.setURINamespace(t.getString("namespace"));
        }

        if (t.has("extends")) {
            List<String> ancestors = null;
            String base = t.getString("extends");
            if (base.length() > 0) {
                String[] parentIds = null;
                if (base.indexOf(",") != -1) {
                    parentIds = base.split(",");
                } else {
                    parentIds = new String[1];
                    parentIds[0] = base;
                }
                ancestors = new ArrayList<String>();

                for (int j = 0; j < parentIds.length; j++) {
                    ancestors.add(parentIds[j].trim());
                }
            }

            temp.setAncestors(ancestors);
        }

        if (t.has("overrides")) {

            List<TemplateOverride> overrides = new ArrayList<TemplateOverride>();
            JSONArray joa = t.getJSONArray("overrides");
            for (int z = 0; z < joa.length(); z++) {
                TemplateOverride tor = new TemplateOverride();
                JSONObject toro = joa.getJSONObject(z);
                if (toro.has("test")) {
                    tor.setTest(toro.getString("test"));
                }
                if (toro.has("uaTest")) {
                    tor.setUATest(toro.getString("uaTest"));
                }
                if (toro.has("import")) {
                    tor.setImportURI(toro.getString("import"));
                }
                overrides.add(tor);
            }
            temp.setTemplateOverrides(overrides);
        }

        if (t.has("scripts")) {

            JSONObject bsjo = t.getJSONObject("scripts");

            processURIResources(ResourceURI.SCRIPT, bsjo, temp, baseURI);
        }

        if (t.has("styles")) {
            JSONObject bsjo = t.getJSONObject("styles");

            processURIResources(ResourceURI.LINK, bsjo, temp, baseURI);
        }

        if (t.has("properties")) {

            Map<String, IProperty> properties = null;
            JSONObject po = t.getJSONObject("properties");
            properties = new HashMap<String, IProperty>();

            Iterator<String> jit = po.keys();
            while (jit.hasNext()) {

                String name = jit.next();
                JSONObject so = po.getJSONObject(name);
                int type = IProperty.STRING;
                String value = so.getString("value");

                if (so.has("type")) {

                    String typeString = so.getString("type");

                    if ("string".equals(typeString.toLowerCase())) {
                        type = IProperty.STRING;
                    } else if ("include".equals(typeString.toLowerCase())) {
                        type = IProperty.INCLUDE;
                    }
                }

                IProperty pi = new Property(name, value, type, baseURI, temp.getId());

                if (so.has("timeout")) {
                    long timeout = so.getLong("timeout");
                    pi.setTimeout(timeout);
                }
                if (so.has("id")) {
                    pi.setId(so.getString("id"));
                }
                if (so.has("uaTest")) {
                    pi.setUATest(so.getString("uaTest"));
                }
                if (so.has("test")) {
                    pi.setTest(so.getString("test"));
                }
                if (so.has("defer")) {
                    pi.setDefer(so.getBoolean("defer"));
                }
                if (so.has("deferContent")) {
                    pi.setDeferContent(new StringBuffer(so.getString("deferContent")));
                }
                properties.put(name, pi);
            }
            temp.setProperties(properties);
        }

    } catch (JSONException e) {
        getLogger().log(Level.SEVERE, "Error parsing configuration.", e);
    }

}

From source file:com.xebia.incubator.xebium.RemoteWebDriverBuilder.java

private Map<String, String> jsonObjectToMap(JSONObject jsonObject) throws JSONException {
    // Assume you have a Map<String, String> in JSONObject
    @SuppressWarnings("unchecked")
    Iterator<String> nameItr = jsonObject.keys();
    Map<String, String> outMap = new HashMap<String, String>();
    while (nameItr.hasNext()) {
        String name = nameItr.next();
        outMap.put(name, jsonObject.getString(name));
    }// w  w  w.  j  a va2 s .c om

    String platform = outMap.get(PLATFORM);
    if (platform != null) {
        outMap.put(PLATFORM, platform.toUpperCase());
    }

    return outMap;
}

From source file:org.jabsorb.ng.serializer.impl.DictionarySerializer.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  a 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");
    }

    // Class compatibility check
    if (!classNameCheck(java_class)) {
        throw new UnmarshallException("not a Dictionary");
    }

    // JSON Format check
    JSONObject jsonmap;
    try {
        jsonmap = jso.getJSONObject("map");
    } catch (final JSONException e) {
        throw new UnmarshallException("map missing", 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.DictionarySerializer.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 {/*from  w ww .  j  a  v a  2s . co 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 dictionary
    Hashtable<Object, Object> dictionary;
    if (java_class.equals("java.util.Dictionary") || java_class.equals("java.util.Hashtable")) {
        dictionary = new Hashtable<Object, Object>();
    } else if (java_class.equals("java.util.Properties")) {
        dictionary = new Properties();
    } else {
        throw new UnmarshallException("not a Dictionary");
    }

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

    state.setSerialized(o, dictionary);

    final Iterator<?> i = jsonmap.keys();
    String key = null;
    try {
        while (i.hasNext()) {
            key = (String) i.next();
            dictionary.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 dictionary;
}