3

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.

3 Answers 3

2

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"));
Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what I expected.
2

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());
    }

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.