Stack Overflow archive
3 score

Parse json without knowning the keys

score
3
question views
12.9K
license
CC BY-SA 3.0

Possible solution:

java
private HashMap<String, Object> getHashMapFromJson(String json) throws JSONException {
    HashMap<String, Object> map = new HashMap<String, Object>();
    JSONObject jsonObject = new JSONObject(json);
    for (Iterator<String> it = jsonObject.keys(); it.hasNext();) {
        String key = it.next();
        map.put(key, jsonObject.get(key));
    }
    return map;
}

Testing with your example JSON string:

java
private void test() {
    String json = " {\"id\" : 12345, \"value\" : \"123\", \"person\" : \"1\"}";
    try {
        HashMap<String, Object> map = getHashMapFromJson(json);
        for (String key : map.keySet()) {
            Log.i("JsonTest", key + ": " + map.get(key));
        }
    } catch (JSONException e) {
        Log.e("JsonTest", "Failed parsing " + json, e);
    }

}

Output:

json
I/JsonTest(24833): id: 12345
I/JsonTest(24833): value: 123
I/JsonTest(24833): person: 1

Note: This is not ideal and I just wrote it real quick.

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.