Search code examples
javaorg.jsonjavax.json

Converting from javax.json.JsonArray to org.json.JSONArray


Is it possible to convert from the newer JSON libraries to the older org.json ones without having to rely on org.json.simple or GSON?

In the case below, "buttons" is a populated JsonArray and I'm trying to copy it into a JSONArray for legacy code. But the initialization of JSONArray from a stringified value always fails with "A JSONObject text must begin with '{'" because a quote is seen as a first character rather than a curly brace.

JSONArray newButtons = new JSONArray(); for (int i = 0; i < buttons.size(); i++) { JsonString button = buttons.getJsonString(i); newButtons.put(new JSONArray(button.toString())); } return new JSONArray(newButtons);

It doesn't seem like there is any kind of org.json object that I can initialize from a string constructor with a toString() value from the javax.json library. I have managed to move data from org.json structures to javax.json ones, but not vice versa. Is the org.json library too inflexible to do this?


Solution

  • I haven't tried it, but I believe following should work.

    JSONArray newButtons = new JSONArray();
    for (int i = 0; i < buttons.size(); i++) {
        JsonObject button = buttons.getJsonObject(i);
        newButtons.put(new org.json.JSONObject(button.toString()));
    }
    return newButtons;
    

    With the following line you get first the object with index 'i' and then make a JSON String out of it. Your original code rather returns the element 'i' as a value instead of an object.

    JsonString button = buttons.getJsonObject(i).toString();