-
-
Save jometho/ff60d4817145f98fd0f2cd0eff61f081 to your computer and use it in GitHub Desktop.
Simple Java Class to convert Lists/Maps to JSON and vice versa
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SimpleJSON { | |
public static Object toJSON(Object object) throws JSONException { | |
if (object instanceof HashMap) { | |
JSONObject json = new JSONObject(); | |
HashMap map = (HashMap) object; | |
for (Object key : map.keySet()) { | |
json.put(key.toString(), toJSON(map.get(key))); | |
} | |
return json; | |
} else if (object instanceof Iterable) { | |
JSONArray json = new JSONArray(); | |
for (Object value : ((Iterable)object)) { | |
json.add(toJSON(value)); | |
} | |
return json; | |
} else { | |
return object; | |
} | |
} | |
public static boolean isEmptyObject(JSONObject object) { | |
return object.names() == null; | |
} | |
public static HashMap<String, Object> getMap(JSONObject object, String key) throws JSONException { | |
return toMap(object.getJSONObject(key)); | |
} | |
public static ArrayList getList(JSONObject object, String key) throws JSONException { | |
return toList(object.getJSONArray(key)); | |
} | |
public static HashMap<String, Object> toMap(JSONObject object) throws JSONException { | |
HashMap<String, Object> map = new HashMap(); | |
Iterator keys = object.keys(); | |
while (keys.hasNext()) { | |
String key = (String) keys.next(); | |
map.put(key, fromJson(object.get(key))); | |
} | |
return map; | |
} | |
public static ArrayList toList(JSONArray array) throws JSONException { | |
ArrayList list = new ArrayList(); | |
for (int i = 0; i < array.length(); i++) { | |
list.add(fromJson(array.get(i))); | |
} | |
return list; | |
} | |
private static Object fromJson(Object json) throws JSONException { | |
if (json == JSONObject.NULL) { | |
return null; | |
} else if (json instanceof JSONObject) { | |
return toMap((JSONObject) json); | |
} else if (json instanceof JSONArray) { | |
return toList((JSONArray) json); | |
} else { | |
return json; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment