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:org.entrystore.ldcache.util.JsonUtil.java

public static Map<Value, Value> jsonArrayToMap(JSONArray array) {
    Map<Value, Value> result = new HashMap<>();
    for (int i = 0; i < array.length(); i++) {
        try {//from   w w  w  . j  av  a  2 s  .  c  om
            JSONObject obj = array.getJSONObject(i);
            if (obj.keys().hasNext()) {
                String key = (String) obj.keys().next();
                String value = obj.getString(key);
                if (key != null && value != null) {
                    result.put(new URIImpl(NS.expandNS(key)), new URIImpl(NS.expandNS(value)));
                }
            }
        } catch (JSONException e) {
            log.warn(e.getMessage());
            continue;
        }
    }
    return result;
}

From source file:org.entrystore.ldcache.util.JsonUtil.java

public static Map<Value, Value> jsonObjectToMap(JSONObject object) {
    Map<Value, Value> result = new HashMap<>();
    Iterator it = object.keys();
    while (it.hasNext()) {
        String key = (String) it.next();
        try {/*  w  w  w.  j  a v  a2s . c om*/
            String value = object.getString(key);
            if (key != null && value != null) {
                result.put(new URIImpl(NS.expandNS(key)), new URIImpl(NS.expandNS(value)));
            }
        } catch (JSONException e) {
            log.warn(e.getMessage());
            continue;
        }
    }
    return result;
}

From source file:com.github.socialc0de.gsw.android.MainActivity.java

public static Map<String, Object> toMap(JSONObject object) throws JSONException {
    Map<String, Object> map = new HashMap<String, Object>();

    Iterator<String> keysItr = object.keys();
    while (keysItr.hasNext()) {
        String key = keysItr.next();
        Object value = object.get(key);

        if (value instanceof JSONArray) {
            value = toList((JSONArray) value);
        } else if (value instanceof JSONObject) {
            value = toMap((JSONObject) value);
        }//from  w  w  w.j  a  v a 2 s  .  c o  m
        map.put(key, value);
    }
    return map;
}

From source file:com.github.socialc0de.gsw.android.MainActivity.java

public HashMap<String, Category> parseCat(String json) {
    try {//from w w w  . ja v  a 2  s.c om
        JSONObject cat_json = new JSONObject(json);
        HashMap<String, Category> map = new HashMap<String, Category>();

        Iterator<String> keysItr = cat_json.keys();
        while (keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = cat_json.get(key);
            Category cat = new Category();
            if (value instanceof JSONObject) {
                JsonFactory factory = new AndroidJsonFactory();
                cat = factory.fromString(value.toString(), Category.class);
            }
            map.put(key, cat);
        }
        return map;
    } catch (Exception e) {
        Log.d(TAG, "Error", e);
        return null;
    }
}

From source file:org.openqa.selenium.logging.SessionLogs.java

public static SessionLogs fromJSON(JSONObject rawSessionLogs) throws JSONException {
    SessionLogs sessionLogs = new SessionLogs();
    for (Iterator logTypeItr = rawSessionLogs.keys(); logTypeItr.hasNext();) {
        String logType = (String) logTypeItr.next();
        JSONArray rawLogEntries = rawSessionLogs.getJSONArray(logType);
        List<LogEntry> logEntries = new ArrayList<LogEntry>();
        for (int index = 0; index < rawLogEntries.length(); index++) {
            JSONObject rawEntry = rawLogEntries.getJSONObject(index);
            logEntries.add(new LogEntry(LogLevelMapping.toLevel(rawEntry.getString("level")),
                    rawEntry.getLong("timestamp"), rawEntry.getString("message")));
        }//from w w  w . j a v a 2  s.c  o  m
        sessionLogs.addLog(logType, new LogEntries(logEntries));
    }
    return sessionLogs;
}

From source file:com.ultramegatech.ey.UpdateService.java

/**
 * Convert a JSONObject to a ContentValues object.
 * //  w w w.java  2 s .co m
 * @param object
 * @return ContentValues containing data from the JSONObject
 * @throws JSONException 
 */
private static ContentValues parseJsonObject(JSONObject object) throws JSONException {
    final ContentValues values = new ContentValues();

    final Iterator keys = object.keys();
    while (keys.hasNext()) {
        addValue(values, object, keys.next().toString());
    }

    return values;
}

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

@Override
@SuppressWarnings("unchecked")
public JSONObject getPathsJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache,
        String rootPath, JSONObject restrictions)
        throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {//from w  w  w . java  2  s.  c o  m
        JSONObject out = new JSONObject();
        List<String> listitems = new ArrayList<String>();
        Iterator rit = restrictions.keys();
        StringBuffer args = new StringBuffer();
        while (rit.hasNext()) {
            String key = (String) rit.next();
            FieldSet fs = r.getFieldTopLevel(key);
            if (!(fs instanceof Field))
                continue;
            String filter = ((Field) fs).getServicesFilterParam();
            if (filter == null)
                continue;
            args.append('&');
            args.append(filter);
            args.append('=');
            args.append(URLEncoder.encode(restrictions.getString(key), "UTF-8"));
        }
        // pagination
        String tail = args.toString();

        String path = getRestrictedPath(r.getServicesURL(), restrictions, r.getServicesSearchKeyword(), tail,
                false, "");

        if (r.hasSoftDeleteMethod()) {
            path = softpath(path);
        }
        if (r.hasHierarchyUsed("screen")) {
            path = hierarchicalpath(path);
        }

        JSONObject data = getListView(creds, cache, path, r.getServicesListPath(), "csid", false, r);
        return data;
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e.getStatus(),
                e.getUrl(), e);
    } catch (UnsupportedEncodingException e) {
        throw new UnderlyingStorageException("Exception building query" + e.getLocalizedMessage(), e);
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Exception building query" + e.getLocalizedMessage(), e);
    }
}

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

@Override
@SuppressWarnings("unchecked")
public String[] getPaths(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache,
        String rootPath, JSONObject restrictions)
        throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {/*from w w w.jav a 2 s.  c  o m*/
        List<String> out = new ArrayList<String>();
        Iterator rit = restrictions.keys();
        StringBuffer args = new StringBuffer();
        while (rit.hasNext()) {
            String key = (String) rit.next();
            FieldSet fs = r.getFieldTopLevel(key);
            if (!(fs instanceof Field))
                continue;
            String filter = ((Field) fs).getServicesFilterParam();
            if (filter == null)
                continue;
            args.append('&');
            args.append(filter);
            args.append('=');
            args.append(URLEncoder.encode(restrictions.getString(key), "UTF-8"));
        }
        // pagination

        String tail = args.toString();
        String path = getRestrictedPath(r.getServicesURL(), restrictions, r.getServicesSearchKeyword(), tail,
                false, "");

        ReturnedDocument doc = conn.getXMLDocument(RequestMethod.GET, path, null, creds, cache);
        if (doc.getStatus() < 200 || doc.getStatus() > 399)
            throw new UnderlyingStorageException("Cannot retrieve account list", doc.getStatus(), path);
        Document list = doc.getDocument();
        List<Node> objects = list.selectNodes(r.getServicesListPath());
        for (Node object : objects) {
            List<Node> fields = object.selectNodes("*");
            String csid = object.selectSingleNode("csid").getText();
            for (Node field : fields) {
                if ("csid".equals(field.getName())) {
                    int idx = csid.lastIndexOf("/");
                    if (idx != -1)
                        csid = csid.substring(idx + 1);
                    out.add(csid);
                } else if ("uri".equals(field.getName())) {
                    // Skip!
                } else {
                    String json_name = view_map.get(field.getName());
                    if (json_name != null) {
                        String value = field.getText();
                        // XXX hack to cope with multi values
                        if (value == null || "".equals(value)) {
                            List<Node> inners = field.selectNodes("*");
                            for (Node n : inners) {
                                value += n.getText();
                            }
                        }
                        setGleanedValue(cache, r.getServicesURL() + "/" + csid, json_name, value);
                    }
                }
            }
        }
        return out.toArray(new String[0]);
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e.getStatus(),
                e.getUrl(), e);
    } catch (UnsupportedEncodingException e) {
        throw new UnderlyingStorageException("Exception building query" + e.getLocalizedMessage(), e);
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Exception building query" + e.getLocalizedMessage(), e);
    }
}

From source file:com.snappy.couchdb.CouchDBHelper.java

/**
 * Parses multi RecentActivity JSON Objects
 * /*from   w w  w  .  j  av  a  2s . c om*/
 * @param recentActivityListJson
 * @return
 * @throws SpikaException 
 * @throws IOException 
 * @throws ClientProtocolException 
 */
public static List<RecentActivity> parseMultiRecentActivityObjects(JSONObject recentActivityListJson)
        throws ClientProtocolException, IOException, SpikaException {

    List<RecentActivity> recentActivityList = new ArrayList<RecentActivity>();

    @SuppressWarnings("unchecked")
    Iterator<String> iterator = recentActivityListJson.keys();
    while (iterator.hasNext()) {
        String key = iterator.next();
        try {
            JSONObject recentActivityJson = recentActivityListJson.getJSONObject(key);
            RecentActivity recentActivity = new RecentActivity();
            recentActivity = sGsonExpose.fromJson(recentActivityJson.toString(), RecentActivity.class);

            if (recentActivityJson.has(Const.NOTIFICATIONS)) {
                JSONArray notificationsJson = recentActivityJson.getJSONArray(Const.NOTIFICATIONS);
                recentActivity.set_notifications(parseMultiNotificationObjects(notificationsJson));
            }
            recentActivityList.add(recentActivity);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return recentActivityList;
}

From source file:com.snappy.couchdb.CouchDBHelper.java

/**
 * Parse multi JSON objects of type GroupCategory
 * //w  ww .  j  a v  a2s. c o m
 * @param json
 * @return
 * @throws JSONException 
 */
public static List<GroupCategory> parseMultiGroupCategoryObjects(JSONObject json) throws JSONException {
    List<GroupCategory> groupCategories = null;

    if (json != null) {

        if (json.has(Const.ERROR)) {
            appLogout(null, false, isInvalidToken(json));
            return null;
        }

        groupCategories = new ArrayList<GroupCategory>();

        JSONArray rows = json.getJSONArray(Const.ROWS);

        for (int i = 0; i < rows.length(); i++) {

            JSONObject row = rows.getJSONObject(i);
            String key = row.getString(Const.KEY);

            if (!key.equals(Const.NULL)) {

                JSONObject groupCategoryJson = row.getJSONObject(Const.VALUE);

                GroupCategory groupCategory = sGsonExpose.fromJson(groupCategoryJson.toString(),
                        GroupCategory.class);

                if (groupCategoryJson.has(Const.ATTACHMENTS)) {
                    List<Attachment> attachments = new ArrayList<Attachment>();

                    JSONObject json_attachments = groupCategoryJson.getJSONObject(Const.ATTACHMENTS);

                    @SuppressWarnings("unchecked")
                    Iterator<String> keys = json_attachments.keys();
                    while (keys.hasNext()) {
                        String attachmentKey = keys.next();
                        try {
                            JSONObject json_attachment = json_attachments.getJSONObject(attachmentKey);
                            Attachment attachment = sGsonExpose.fromJson(json_attachment.toString(),
                                    Attachment.class);
                            attachment.setName(attachmentKey);
                            attachments.add(attachment);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    groupCategory.setAttachments(attachments);
                }

                groupCategories.add(groupCategory);
            }
        }
    }

    return groupCategories;
}