我针对同一问题找到的所有答案都涉及org.json.JSONArray
。我需要 javax.json.JsonArray 的解决方案。
我有两个JSON数组,当我尝试将它们与array1.addAll(array2)
合并时,会得到一个java.lang.UnsupportedOperationException
。
...
JsonObject users = getUsers(searchBase, filter, (String[]) null);
...
final JsonObject guests = getUsers(searchBase, filter, (String[]) null);
users.getJsonArray("Resources").addAll(guests.getJsonArray("Resources"));
...
我回来的JsonObjects
(用户和来宾)都具有以下形式:
{
"startIndex": 1,
"totalResults": 7,
"itemsPerPage": 7,
"schemas": [
"urn:ietf:params:scim:api:messages:2.0:ListResponse"
],
"Resources": [
{
"attr1": "value1",
"attr2": "value2",
"attr3": "value3",
"attr4": "value4",
},
{
"attr1": "value5",
"attr2": "value6",
"attr3": "value7",
"attr4": "value8",
},
...
]
}
为什么会出现此错误?
那我该怎么做才能合并它们?
编辑: 正确的答案是tonakai之一。不幸的是,这是一条评论,我无法将其设置为可接受的答案。
答案 0 :(得分:1)
我想您正在寻找JsonArrayBuilder
。
以下代码对我有用:
import java.io.*;
import javax.json.*;
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException {
InputStream fileInputStream = new FileInputStream("ABSOLUTE_PATH_TO_FILE\\jsonData.json");
JsonReader jsonReader = Json.createReader(fileInputStream);
JsonObject jsonObject = jsonReader.readObject();
JsonArrayBuilder users = Json.createArrayBuilder(jsonObject.getJsonArray("Resources"));
JsonArrayBuilder guests = Json.createArrayBuilder(jsonObject.getJsonArray("Resources"));
users.addAll(guests);
System.out.println(users.build());
jsonReader.close();
fileInputStream.close();
}
}
我在这里使用的文件是根据您在问题中提供的JSON创建的:
{
"startIndex":1,
"totalResults":7,
"itemsPerPage":7,
"schemas":[
"urn:ietf:params:scim:api:messages:2.0:ListResponse"
],
"Resources":[
{
"attr1":"value1",
"attr2":"value2",
"attr3":"value3",
"attr4":"value4"
},
{
"attr1":"value5",
"attr2":"value6",
"attr3":"value7",
"attr4":"value8"
}
]
}