Java – Convert nested arrays to JSON

Convert nested arrays to JSON… here is a solution to the problem.

Convert nested arrays to JSON

I have a nested array in Java, like this:

String [] [] x;

In my code, I convert it to a JSON string to pass it over the @JavascriptInterface bridge to a javascript running in WebView using the following code:

String ret = (new JSONArray(Arrays.asList(x))).toString();

This works fine on newer devices, but I experience very strange behavior when testing older devices. Instead of creating a nice string like this:

"[ [ 1.234, 5, 7 ], [ 23.456, 7, 8 ] ]"

It is creating a string that looks like this:

'["[Ljava.lang.String; @405ba988"]'

As far as I know, all the objects I use (JSONArray, Arrays) and corresponding member functions (toString, asList) have been around since API level 1.

Am I doing something wrong, or am I missing something I need to do to adapt to earlier versions of Android?

Solution

Prior to Android 4.4 (API 19). following is the constructor code:

public JSONArray(Collection copyFrom) {
    this();
    Collection<?> copyFromTyped = (Collection<?>) copyFrom;
    values.addAll(copyFromTyped);
}

As you can see, it just adds the members of the collection, which is why you get '["[Ljava.lang.String; @405ba988']' for reasons why they are not additionally processed

Added and changed some features in Android 4.4 (API 19) The wrap method is added to JSONObject that can handle arrays, the same constructor in JSONArray is changed Use it:

public JSONArray(Collection copyFrom) {
    this();
    if (copyFrom != null) {
        for (Iterator it = copyFrom.iterator(); it.hasNext();) {
            put(JSONObject.wrap(it.next()));
        }
    }
}

Related Problems and Solutions