java - Plain Json String to HashMap -
java - Plain Json String to HashMap -
there quite few questions raised convert json hashmap
. hope helps everybody.
the next code convert direct values or array
of values, hashmap
.
// function called recursively
private static map getmap(jsonobject object, string json) throws exception { map<string, object> map = new hashmap<string, object>(); object jsonobject = null; iterator<string> keys = object.keys(); while (keys.hasnext()) { string key = keys.next(); object value = object.get(key); if (value instanceof jsonobject) { map.put(key, getmap((jsonobject) value, json)); continue; } // if value in form of array if (value instanceof jsonarray) { jsonarray array = ((jsonarray) value); list list = new arraylist(); (int = 0 ; < array.length() ; i++) { jsonobject = array.get(i); if (jsonobject instanceof jsonobject) { list.add(getmap((jsonobject) jsonobject, json)); } else { list.add(jsonobject); } } map.put(key, list); continue; } map.put(key, value); } homecoming map; }
// calling method
public static map<string, object> convertjsontomap(string json) { map<string, object> map = new hashmap<string, object>(); jsonobject jsonobject = null; seek { if (null != json) { jsonobject = new jsonobject(json); map = getmap(jsonobject, json); } } grab (exception e) { throw new systemexception("unable read json object"); // todo : handle exception } homecoming map; }
java json hashmap
Comments
Post a Comment