简体   繁体   中英

How to merge two JsonArray?

All the answers I found for the same question involve org.json.JSONArray . I need a solution for javax.json.JsonArray .

I have two JSON arrays and when I try to merge them with array1.addAll(array2) I get an 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"));
...

The JsonObjects (users and guests) I get back have both this form:

{
    "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",
        },
        ...
    ]
}

Why do I get this error?

How do I have to do to merge them then?

EDIT: The correct answer is the one of tonakai. Unfortunately it is a comment and I cannot set it as the accepted answer.

I guess you are looking for JsonArrayBuilder .

Following code worked for me:

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

The file that I used here was created based on the JSON you provided in the question:

{
   "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"
      }
   ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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