简体   繁体   English

JSONArray中的JSONObject

[英]JSONObject inside JSONArray

I'm trying to put a JSONObject inside a JSONArray in Java. 我正在尝试将JSONObject放入Java的JSONArray中。 Here is my two objects: 这是我的两个对象:

JSONArray: JSONArray:

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

JSONObject: 的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. “事件”键值大多数位于JSONArray中的唯一元素之内,而不是另一个元素。

The JSONArray contains one JSONObject . JSONArray包含一个JSONObject When you jsonArray.put(jsonObject); 当你jsonArray.put(jsonObject); you are adding it to the JSONArray , not to the JSONObject in the JSONArray . 你将它添加到JSONArray ,不给JSONObjectJSONArray

This will add the jsonObject to the first JSONObject in your JSONArray 这将增加jsonObject到第一JSONObjectJSONArray

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

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

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将在索引为0的Object中创建一个名为“ events”的新字段。

 jsonArray[0].events = jsonObject.events;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM