Recursivey Parsing JSON String to HashMap
Json String can contain JsonArray, JsonObject etc.
package com.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
public class TestJson{
public static void main(String args[]) throws Exception {
JSONObject jsonObject = new JSONObject(
"{\"A\":\"M1\",\"Data\":[ {\"B\":[{ \"B1\":\"111\",\"B2\":\"Warning \"},{ \"B1\":\"222\",\"B2\":\"Warning \"}],\"C\":[{\"c1\":\"IL2\",\"c2\":\"[0.750183,0.00933380975964486]\"},{\"c1\":\"IL1b\",\"c2\":\"[0.750183,-1.5216938335421]\"}]}]}");
System.out.println(getMap(jsonObject));
}
private static Map getMap(JSONObject object) {
Map<String, Object> map = new HashMap<String, Object>();
Object jsonObject = null;
String key = null;
Object value = null;
try {
Iterator<String> keys = object.keys();
while (keys.hasNext()) {
key = null;
value = null;
key = keys.next();
if (null != key && !object.isNull(key)) {
value = object.get(key);
}
if (value instanceof JSONObject) {
map.put(key, getMap((JSONObject) value));
continue;
}
if (value instanceof JSONArray) {
JSONArray array = ((JSONArray) value);
List list = new ArrayList();
for (int i = 0 ; i < array.length() ; i++) {
jsonObject = array.get(i);
if (jsonObject instanceof JSONObject) {
list.add(getMap((JSONObject) jsonObject));
} else {
list.add(jsonObject);
}
}
map.put(key, list);
continue;
}
map.put(key, value);
}
} catch (Exception e) {
System.out.println(e);
}
return map;
}
}
How to avoid extra POJO's / Classes
package com.package;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
public class Test{
public static void main(String[] args) {
String json = "[{\"givenName\": \"Adrienne H.\",\"surname\": \"Kovacs\"},{\"givenName\": \"Philip\",\"surname\": \"Moons\"}]";
ObjectMapper mapper = new ObjectMapper();
List<Author> list = new ArrayList<Author>();
try {
list = mapper.readValue(json, TypeFactory.defaultInstance().constructCollectionType(List.class, Author.class));
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(list);
}
}
So here i do not need to map List<Author> inside any other class.
No comments:
Post a Comment