Java 将列表中的以下值合并为单个值
我想将下面的所有对象递归地合并为一个对象。每次我为每次迭代运行代码时,我都会收到一个字符串对象,并将它们存储在一个列表中。列表如下所示: bean[String1,String2,String3]。这三个字符串将合并为单个字符串对象 第1条:Java 将列表中的以下值合并为单个值,java,json,Java,Json,我想将下面的所有对象递归地合并为一个对象。每次我为每次迭代运行代码时,我都会收到一个字符串对象,并将它们存储在一个列表中。列表如下所示: bean[String1,String2,String3]。这三个字符串将合并为单个字符串对象 第1条: [code=100, response= { "testObjects": [ { "updated": [ { "att
[code=100,
response=
{
"testObjects": [
{
"updated": [
{
"attributes": {},
"id": "123"
},
{
"attributes": {},
"id": "456"
}
],
"timeCheckQuery": null,
"query": null,
"message": null,
"error": null,
"deleted": null,
"agentId": null,
"added": null
}
],
"message": null,
"error": null
}
]
第2条:
[code=100,
response=
{
"testObjects": [
{
"updated": [
{
"attributes": {},
"id": "789"
},
{
"attributes": {},
"id": "759"
}
],
"timeCheckQuery": null,
"query": null,
"message": null,
"error": null,
"deleted": null,
"agentId": null,
"added": null
}
],
"message": null,
"error": null
}
]
第3条:
[code=100,
response=
{
"testObjects": [
{
"updated": [
{
"attributes": {},
"id": "242"
},
{
"attributes": {},
"id": "951"
}
],
"timeCheckQuery": null,
"query": null,
"message": null,
"error": null,
"deleted": null,
"agentId": null,
"added": null
}
],
"message": null,
"error": null
}
]
输出:
[code=300,
response=
{
"testObjects": [
{
"updated": [
{
"attributes": {},
"id": "123"
},
{
"attributes": {},
"id": "456"
},
{
"attributes": {},
"id": "789"
},
{
"attributes": {},
"id": "759"
},
{
"attributes": {},
"id": "242"
},
{
"attributes": {},
"id": "951"
}
],
"timeCheckQuery": null,
"query": null,
"message": null,
"error": null,
"deleted": null,
"agentId": null,
"added": null
}
],
"message": null,
"error": null
}
]
您可以将第一个对象序列化为json字符串,然后将该字符串与下一个序列化的对象一起追加,依此类推。updated”字段的值似乎是JsonArray结构 您需要做的是使用一个全局数组,将所有响应中的值(“updated”字段的值)添加到单个JsonArray中 使用Gson库,您可以按如下方式执行
JsonArray jsonarray = new JsonArray();
jsonarray.addAll(jsonObject1.get("updated").getAsJsonArray());
jsonarray.addAll(jsonObject2.get("updated").getAsJsonArray());
jsonarray.addAll(jsonObject2.get("updated").getAsJsonArray());
现在,您可以根据需要在任何对象中使用此JsonArray。此JsonArray的可能副本应该是注释,而不是答案。