[java] Convert JSONObject to Map

I have a JSONObject with some attributes that I want to convert into a Map<String, Object>

Is there something that I can use from the json.org or ObjectMapper?

This question is related to java json map jsonobject

The answer is


Note to the above solution (from A Paul): The solution doesn't work, cause it doesn't reconstructs back a HashMap< String, Object > - instead it creates a HashMap< String, LinkedHashMap >.

Reason why is because during demarshalling, each Object (JSON marshalled as a LinkedHashMap) is used as-is, it takes 1-on-1 the LinkedHashMap (instead of converting the LinkedHashMap back to its proper Object).

If you had a HashMap< String, MyOwnObject > then proper demarshalling was possible - see following example:

ObjectMapper mapper = new ObjectMapper();
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, MyOwnObject.class);
HashMap<String, MyOwnObject> map = mapper.readValue(new StringReader(hashTable.toString()), mapType);

The best way to convert it to HashMap<String, Object> is this:

HashMap<String, Object> result = new ObjectMapper().readValue(jsonString, new TypeReference<Map<String, Object>>(){}));

You can use Gson() (com.google.gson) library if you find any difficulty using Jackson.

HashMap<String, Object> yourHashMap = new Gson().fromJson(yourJsonObject.toString(), HashMap.class);

Found out these problems can be addressed by using

ObjectMapper#convertValue(Object fromValue, Class<T> toValueType)

As a result, the origal quuestion can be solved in a 2-step converison:

  1. Demarshall the JSON back to an object - in which the Map<String, Object> is demarshalled as a HashMap<String, LinkedHashMap>, by using bjectMapper#readValue().

  2. Convert inner LinkedHashMaps back to proper objects

ObjectMapper mapper = new ObjectMapper(); Class clazz = (Class) Class.forName(classType); MyOwnObject value = mapper.convertValue(value, clazz);

To prevent the 'classType' has to be known in advance, I enforced during marshalling an extra Map was added, containing <key, classNameString> pairs. So at unmarshalling time, the classType can be extracted dynamically.


org.json.JSONObject#toMap() will do to work


This is what worked for me:

    public static Map<String, Object> toMap(JSONObject jsonobj)  throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();
        Iterator<String> keys = jsonobj.keys();
        while(keys.hasNext()) {
            String key = keys.next();
            Object value = jsonobj.get(key);
            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            } else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }   
            map.put(key, value);
        }   return map;
    }

    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }
            else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }   return list;
}

Most of this is from this question: How to convert JSONObject to new Map for all its keys using iterator java


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to map

Using array map to filter results with if conditional In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda? UnmodifiableMap (Java Collections) vs ImmutableMap (Google) Convert JSONObject to Map Convert Map<String,Object> to Map<String,String> iterate through a map in javascript Iterator over HashMap in Java Simple dictionary in C++ Create Map in Java Map with Key as String and Value as List in Groovy

Examples related to jsonobject

Delete an element in a JSON object Convert JSONObject to Map convert ArrayList<MyCustomClass> to JSONArray