-
-
Save mohanrajtrade/7ba2b84ffff9d488a469bd8248136c08 to your computer and use it in GitHub Desktop.
Convert Android JSONObject/JSONArray to a standard Map/List.
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
| import org.json.JSONArray; | |
| import org.json.JSONException; | |
| import org.json.JSONObject; | |
| import java.util.*; | |
| public class JsonHelper { | |
| public static Map<String, Object> toMap(JSONObject object) throws JSONException { | |
| Map<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 List toList(JSONArray array) throws JSONException { | |
| List 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 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