diff --git a/JSONArray.java b/JSONArray.java index f29085b..702742c 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -28,11 +28,9 @@ import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Array; -import java.math.*; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.*; /** * A JSONArray is an ordered sequence of values. Its external text form is a @@ -1130,4 +1128,29 @@ public class JSONArray implements Iterable { throw new JSONException(e); } } + + /** + * Returns a java.util.List containing all of the elements in this array. + * If an element in the array is a JSONArray or JSONObject it will also + * be converted. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return a java.util.List containing the elements of this array + */ + public List toList() { + List results = new ArrayList(this.myArrayList.size()); + for (Object element : this.myArrayList) { + if (element == null || JSONObject.NULL.equals(element)) { + results.add(null); + } else if (element instanceof JSONArray) { + results.add(((JSONArray) element).toList()); + } else if (element instanceof JSONObject) { + results.add(((JSONObject) element).toMap()); + } else { + results.add(element); + } + } + return results; + } } diff --git a/JSONObject.java b/JSONObject.java index 1ce2540..444e4fa 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -32,15 +32,8 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; -import java.util.Collection; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.ResourceBundle; -import java.util.Set; /** * A JSONObject is an unordered collection of name/value pairs. Its external @@ -1838,4 +1831,31 @@ public class JSONObject { throw new JSONException(exception); } } + + /** + * Returns a java.util.Map containing all of the entrys in this object. + * If an entry in the object is a JSONArray or JSONObject it will also + * be converted. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return a java.util.Map containing the entrys of this object + */ + public Map toMap() { + Map results = new HashMap<>(); + for (Entry entry : this.map.entrySet()) { + Object value; + if (entry.getValue() == null || NULL.equals(entry.getValue())) { + value = null; + } else if (entry.getValue() instanceof JSONObject) { + value = ((JSONObject) entry.getValue()).toMap(); + } else if (entry.getValue() instanceof JSONArray) { + value = ((JSONArray) entry.getValue()).toList(); + } else { + value = entry.getValue(); + } + results.put(entry.getKey(), value); + } + return results; + } }