aseolin
aseolin

Reputation: 1200

JSONObject inside JSONArray

I'm trying to put a JSONObject inside a JSONArray in Java. Here is my two objects:

JSONArray:

[{
    "url": null,
    "flag": "0",
    "read": "0",
    "time": 2000,
    "exp": null,
    "population": 10
}]

JSONObject:

{
"events": [
    {
        "color": "Green",
        "event": "Restart"
    },
    {
        "color": "Black",
        "event": "Shutdown"
    },
    {
        "color": "White",
        "event": "Read"
    }       
]
}

Expected result:

[
{
    "url": null,
    "flag": "0",
    "read": "0",
    "time": 2000,
    "exp": null,
    "population": 10,
    "events": [
        {
            "color": "Green",
            "event": "Restart"
        },
        {
            "color": "Black",
            "event": "Shutdown"
        },
        {
            "color": "White",
            "event": "Read"
        }
    ]
}
]

I tried to use this code, but the result is not ok:

jsonArray.put(jsonObject);

Unexpected result:

[
{
    "url": null,
    "flag": "0",
    "read": "0",
    "time": 2000,
    "exp": null,
    "population": 10
},
{
    "events": [
        {
            "color": "Green",
            "event": "Restart"
        },
        {
            "color": "Black",
            "event": "Shutdown"
        },
        {
            "color": "White",
            "event": "Read"
        }
    ]
}
]

The "events" key-value most be inside the unique element in JSONArray, not as another element.

Upvotes: 3

Views: 11225

Answers (3)

Codebender
Codebender

Reputation: 14471

You need,

((JSONObject) jsonArray.get(0)).put("events", jsonObject.get("events"));

Or, in a more generalized form,

    for (Map.Entry entry : (Set<Map.Entry>) jsonObject.entrySet()) {
        ((JSONObject) jsonArray.get(0)).put(entry.getKey(), entry.getValue());
    }

Upvotes: 2

Panagiotis Stoupos
Panagiotis Stoupos

Reputation: 140

I did not tested the code but I think this would work. Try it if you want. jsonArray[0].events will create a new field named 'events' in the 0 indexed Object.

 jsonArray[0].events = jsonObject.events;

Upvotes: 0

Ian
Ian

Reputation: 159

The JSONArray contains one JSONObject. When you jsonArray.put(jsonObject); you are adding it to the JSONArray, not to the JSONObject in the JSONArray.

This will add the jsonObject to the first JSONObject in your JSONArray

jsonArray.getJsonObject(0).put("events",jsonObject.get("events"));

Upvotes: 2

Related Questions