Search code examples
javajsonorg.json

How would I convert an element of a JSONObject to a single element array?


I am using org.json.JSONObject and have a json object defined that was converted from XML. I want to be able to convert one of the elements of the JSON to a single element array, but am unclear on how to do this. For example, say I have the following json:

{
    "heading": "value",
    "numbers": [1,2,3],
    "onevalarray": "MyVal"
}

stored in an org.json.JSONObject object. However, I want the element "onevalarray" to be a single element array:

{
    "heading": "value",
    "numbers": [1,2,3],
    "onevalarray": ["MyVal"]
}

How would I accomplish this?


Solution

  • Call the method getJsonArray in the JSONbject object and specify the name of the property in the JSONObject which has the JSONArray in it like this:

    Imagine that myJsonObject has this:

    {"heading": "value", "numbers": [1,2,3], "onevalarray": "MyVal"}
    

    And you want a JSONArray with onevalarray data. Try it:

     JSONArray jsonArray = myJsonObject.getJSONArray("onevalarray");
    

    Once you have the value of the onevalarray in the onevalarray JSONArray then remove the onevalarray in the original array and the put it again in this way:

    myJsonObject.remove("onevalarray");
    
    myJsonObject.put("onevalarray", jsonArray);