Convert JSON String into Map using Streaming API of Jackson


Jackson is a good performance rich java library for JSON processing (parsing/generation). more about Jackson at github home page. The Streaming API of Jackson library is the fastest way to parse/generate a JSON. While using JSON there is sometimes a requirement to convert JSON String into a Object. For small string this seems to be a piece of cake, but for long and complex JSON strings things get a bit hairy when using streaming API. Jackson library has a ObjectMapper which does this job very simple but if you like using Streaming API for parsing JSON String following is some piece of code for you:

Following code was compiled using jackson-core-2.2.3.jar which can be downloaded here.

===================JsonStreaming.java============================

package test;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
/**
 *
 * @author dominic
 */
public class JsonStreaming {
    public static void main(String[] args) {
        String JSONString = “{\n”
                + ” \”name\”:\”dominic\”,\n”
                + ” \”age\”:29,\n”
                + ” \”messages\”:[\”msg 1\”,\”msg 2\”,\”msg 3\”]\n”
                + “}”;
        JsonStreaming jsontest = new JsonStreaming();
        Map<String, Object> jsonmap = jsontest.parseComplexJSON(JSONString);
        for (String key : jsonmap.keySet()) {
            if (jsonmap.get(key) instanceof ArrayList) {
                ListIterator litr = ((ArrayList) jsonmap.get(key)).listIterator();
                System.out.println(key + “:”);
                while (litr.hasNext()) {
                    System.out.println(“:: ” + litr.next());
                }
            } else {
                System.out.println(key + ” : ” + jsonmap.get(key));
            }
        }
    }
    public Map<String, Object> parseComplexJSON(String jsonstr) {
        Map<String, Object> respdata = new HashMap<String, Object>();
        JsonFactory jfac = new JsonFactory();
        try {
            JsonParser jParser = jfac.createParser(jsonstr);
            while (jParser.nextToken() != null) {
                if (jParser.getCurrentToken() == JsonToken.START_ARRAY) {
                    respdata.put(“result”, readJSONArray(jParser));
                } else if (jParser.getCurrentToken() == JsonToken.START_OBJECT) {
                    return readJSONObject(jParser);
                } else {
                    respdata.put(jParser.getCurrentName(), jParser.getText());
                }
            }
            jParser.close();
        } catch (Exception ex) {
            System.out.println(“Excpetion : ” + ex);;
        }
        return respdata;
    }
    public Map<String, Object> readJSONObject(JsonParser jParser) {
        Map<String, Object> jsonobject = new HashMap<String, Object>();
        int jsoncounter = 1;
        if (jParser.getCurrentToken() == JsonToken.START_OBJECT) {
            try {
                while (jParser.nextToken() != JsonToken.END_OBJECT) {
                    if (jParser.getCurrentToken() == JsonToken.START_OBJECT) {
                        Map<String, Object> subjsonobj = readJSONObject(jParser);
                        if (jParser.getCurrentName() != null && !jParser.getCurrentName().trim().isEmpty()) {
                            jsonobject.put(jParser.getCurrentName(), subjsonobj);
                        } else {
                            jsonobject.put(jsoncounter + “”, subjsonobj);
                            jsoncounter++;
                        }
                    } else if (jParser.getCurrentToken() == JsonToken.START_ARRAY) {
                        List<Object> subjsonarray = readJSONArray(jParser);
                        if (jParser.getCurrentName() != null && !jParser.getCurrentName().trim().isEmpty()) {
                            jsonobject.put(jParser.getCurrentName(), subjsonarray);
                        } else {
                            jsonobject.put(jsoncounter + “”, subjsonarray);
                            jsoncounter++;
                        }
                    } else {
                        jsonobject.put(jParser.getCurrentName(), jParser.getText());
                    }
                }
            } catch (Exception ex) {
                System.out.println(“Excpetion : ” + ex);;
            }
        }
        return jsonobject;
    }
    public List<Object> readJSONArray(JsonParser jParser) {
        List<Object> jsonarray = new ArrayList<Object>();
        if (jParser.getCurrentToken() == JsonToken.START_ARRAY) {
            try {
                while (jParser.nextToken() != JsonToken.END_ARRAY) {
                    if (jParser.getCurrentToken() == JsonToken.START_OBJECT) {
                        Map<String, Object> subjsonobj = readJSONObject(jParser);
                        jsonarray.add(subjsonobj);
                    } else if (jParser.getCurrentToken() == JsonToken.START_ARRAY) {
                        List<Object> subjsonarray = readJSONArray(jParser);
                        jsonarray.add(subjsonarray);
                    } else {
                        jsonarray.add(jParser.getText());
                    }
                }
            } catch (Exception ex) {
                System.out.println(“Excpetion : ” + ex);;
            }
        }
        return jsonarray;
    }
}

===================JsonStreaming.java============================

I haven’t tested the above code for very complex JSON strings but it works for most of them. In the code above parseComplexJSON takes in as parameter JSON string and returns a java.util.Map<String, Object> the Object here can be ArrayList to denote corresponding JSONArray. The code uses a lot of recursion to parse JSON String. All JSONObject are converted to Map<String, Object> and all JSONArray are converted to ArrayList<Object>.

Happy Coding!

Further Reading:

http://wiki.fasterxml.com/JacksonStreamingApi  [Streaming API of Jackson]

http://wiki.fasterxml.com/JacksonHome

http://wiki.fasterxml.com/JacksonInFiveMinutes [Jackson Overview in 5 minutes]

Advertisements

About Dominic

J for JAVA more about me : http://about.me/dominicdsouza
This entry was posted in Thechy Stuff and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s