Converting a nested array to JSON

Viewed 192

I've got a nested array in Java, something like this:

String [] [] x;

In my code I'm converting it into a JSON string to pass it across the @JavascriptInterface bridge to javascript running in a WebView using this code:

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

This is working fine on newer devices, but in testing an older device I'm running into very weird behavior. Instead of creating a nice string like this:

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

it's creating a string that looks like this:

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

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

Am I doing something wrong, or is there something I am missing that I need to do to accommodate earlier versions of Android?

1 Answers

Before Android 4.4(api 19) the following was 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, this is why you get '["[Ljava.lang.String;@405ba988"]' no additional processing is done on them.

In Android 4.4(api 19) some functionality was added and changed wrap method was added to JSONObject which can handle an array and the same constructor from JSONArray was changed to use it:

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