Thursday, December 11, 2008

Json to Java

Convert a JSON string into a Java Map or Java List.

Make sure you have included all apache-commons, apache-logging, apache-discovery (and many other apache packaged required by json) and json-lib in your classpath

This class also has a small main function at the bottom, that shows how to use this class.
(Excuse me for the bad formatting, I will figure out how to update this post with a proper formatting.)


import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
*formatting a JSON response into Map and List
*/
public class Json2Java {
private static final int TIMEOUT = 5000; // 5 seconds timeout

//This is how you use it.
public static void main(String a[]) throws Exception {
Json2Java j = new Json2Java();
String jsonStr = "{\"id\":101,\"person\":{\"fname\":\"foo\", \"lname\":\"bar\"}}";
Map<String, Object> resp = j.getMap(jsonStr);
System.out.println("Response message = " + ((Map)resp.get("person")).get("lname"));
}


/**
* getList provides a List representation of the JSON Object
* @param jsonResponse The JSON array string
* @return List of JSONObject.
**/
protected List<Object> getList(String jsonResponse) throws Exception {
List<Object> listResponse = new ArrayList<Object>();
if (jsonResponse.startsWith("[")) {
JSONArray jsonArray = JSONArray.fromObject(jsonResponse);
toJavaList(jsonArray, listResponse);
} else {
throw new Exception("MalFormed JSON Array Response.");
}

return listResponse;
}

/**
* getMap provides a Map representation of the JSON Object
* @param jsonResponse The JSON object string
* @return Map of JSONObject.
**/
protected Map<String, Object> getMap(String jsonResponse ) throws Exception {
Map<String, Object> mapResponse = new HashMap<String, Object>();
if (jsonResponse.startsWith("{")) {
JSONObject jsonObj = JSONObject.fromObject(jsonResponse);
toJavaMap(jsonObj, mapResponse);
} else {
throw new Exception("MalFormed JSON Array Response.");
}
return mapResponse;
}

/**
* toJavaMap converts the JSONObject into a Java Map
* @param o
* JSONObject to be converted to Java Map
* @param b
* Java Map to hold converted JSONObject response.
**/
private static void toJavaMap(JSONObject o, Map<String, Object> b) {
Iterator ji = o.keys();
while (ji.hasNext()) {
String key = (String) ji.next();
Object val = o.get(key);
if (val.getClass() == JSONObject.class) {
Map<String, Object> sub = new HashMap<String, Object>();
toJavaMap((JSONObject) val, sub);
b.put(key, sub);
} else if (val.getClass() == JSONArray.class) {
List<Object> l = new ArrayList<Object>();
JSONArray arr = (JSONArray) val;
for (int a = 0; a < arr.size(); a++) {
Map<String, Object> sub = new HashMap<String, Object>();
Object element = arr.get(a);
if (element instanceof JSONObject) {
toJavaMap((JSONObject) element, sub);
l.add(sub);
} else {
l.add(element);
}
}
b.put(key, l);
} else {
b.put(key, val);
}
}
}

/**
* toJavaList converts JSON's array response into Java's List
* @param ar
* JSONArray to be converted to Java List
* @param ll
* Java List to hold the converted JSONArray response
**/
private static void toJavaList(JSONArray ar, List<Object> ll) {
int i = 0;
while (i < ar.size()) {
Object val = ar.get(i);
if (val.getClass() == JSONObject.class) {
Map<String, Object> sub = new HashMap<String, Object>();
toJavaMap((JSONObject) val, sub);
ll.add(sub);
} else if (val.getClass() == JSONArray.class) {
List<Object> l = new ArrayList<Object>();
JSONArray arr = (JSONArray) val;
for (int a = 0; a < arr.size(); a++) {
Map<String, Object> sub = new HashMap<String, Object>();
Object element = arr.get(a);
if (element instanceof JSONObject) {
toJavaMap((JSONObject) element, sub);
ll.add(sub);
} else {
ll.add(element);
}
}
l.add(l);
} else {
ll.add(val);
}
i++;
}
}
}



4 comments:

  1. Awesome, Had been looking for exactly this thing. Json2java converts nicely. So easy to convert json objects to Java maps and JSON arrays to Java Arrays. Cant get any easier.

    ReplyDelete
  2. Be carefull when comparing classes types. In the method toJavaMap, you are comparing JSONObject.class with the equals operator "var.getClass() == JSONObject.class". I recommendo you, compare it with the equals method instead: JSONObject.class.equals(var.getClass()).

    ReplyDelete
  3. Hi,
    While discussing about HashMap its worth mentioning following questions which frequently asked in Java interviews now days like How HashMap works in Java or How get() method of HashMap works in JAVA very often. on concept point of view these questions are great and expose the candidate if doesn't know deep details.

    Javin
    FIX Protocol tutorial

    ReplyDelete
  4. Nice article , just to add the functionality of Enumeration interface is duplicated by the Iterator interface.
    Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects.

    to read more see here difference between iterator and enumeration

    ReplyDelete