Vineeth Mohan
Vineeth Mohan

Reputation: 19253

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.

Upvotes: 2

Views: 2870

Answers (4)

dawn cho
dawn cho

Reputation: 1

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;
    }
}

Upvotes: 0

Mohit Verma
Mohit Verma

Reputation: 2089

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/

Upvotes: 0

AurA
AurA

Reputation: 12363

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

Upvotes: 1

Boris Strandjev
Boris Strandjev

Reputation: 46943

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)

Upvotes: 2

Related Questions