简体   繁体   中英

Convert complex structure of map and list into JSON

I have a Map>>>> or something similar Map> I need to covert this into JSON.

So my use case would be to convert an object which can be a map or list which has generic element of map or list and this can go recursively to any number of times. The leaf element would be integer or string.

Is there any ready made way i can do this in Java.

Use GSON . It is easy plug-and-play library for serialization/deserialization of JSON. It will handle natively java collections.

It will also help you once you need to deserialize the JSON eventually (however, it needs a bit of more effort toward deserialization of generics)

You can directly create using

Map<String, String> myMap = new HashMap<String, String>();

JSONObject jsonObj = new JSONObject(map);

JSONObject is provided by Json.org

http://www.json.org/javadoc/org/json/JSONObject.html

How about using Jackson's streaming API's to parse json and create object ? Something like this http://www.mkyong.com/java/jackson-streaming-api-to-read-and-write-json/

public static Object jsonMapper(Object obj){
    if (obj instanceof Map) {
        Map map = (Map) obj;
        for (Object entryobj : map.entrySet()) {
            Entry entry = (Entry) entryobj;
            entry.setValue(jsonMapper(entry.getValue()));
        }

        return new JSONObject(map);

    } else if (obj instanceof List) {
        List list = (List) obj;
        for (int i = 0; i< list.size(); i++) {
            Object o = list.get(i);
            list.set(i, jsonMapper(o));
        }

        return new JSONArray(list);
    } else { //string or integer
        return obj;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM