简体   繁体   中英

javax.json: Build a JSONArray from a List<Integer> and add it to a JSONObject

Simple task but I couldn't find a way to do it.

My output JSON needs to be

{
   "id" : "somestring", 
   "nums" : [44,31,87,11,34]
}

I'm using the javax.json library with JSONObject / JsonArray . There is a List<Integer> which comes in with the values for the 2nd field. These aren't objects, these are plain numbers. I don't know how to get a JSONValue from an Integer.

        Map<String, Object> config = new HashMap<String, Object>();
        JsonBuilderFactory factory = Json.createBuilderFactory(config);
        JsonArray jsonArray = (JsonArray) Json.createArrayBuilder();
        for (Integer num: nums) // Assume a List<Integer> nums
            jsonArray.add(..); // What to do here? JSONValue from an Integer?
                               // Can't do jsonArray.add(num)

        // Final Object
        JsonObject value = factory.createObjectBuilder()
            .add("id", id)
            .add("nums", jsonArray); // Link up jsonArray to the 2nd Add

Note - can't add an Integer directly, 在此处输入图片说明

createArrayBuilder method will return JsonArrayBuilder object, you should not do the explicit type casting. So first create array builder and then add Integers to it

JsonArrayBuilder jsonArray = Json.createArrayBuilder();
    for (Integer num: nums) {
        jsonArray.add(num); 
      }

Then finally call build method that will build JsonArray

JsonArray array = jsonArray.build();

FINAL SOLUTION (thanks Deadpool )

        Map<String, Object> config = new HashMap<String, Object>();
        JsonBuilderFactory factory = Json.createBuilderFactory(config);
        JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
        for (Integer num: nums) 
            jsonArrayBuilder.add(temp); // Note: adding to the Array Builder here

        // Now add to the final object
        JsonObject obj = factory.createObjectBuilder()
            .add("id", id)
            .add("nums", jsonArrayBuilder)  /* Note the Array Builder is passed in */
            .build();

        // The full object is complete now and can be printed
        // It looks like: { "id":"string", "nums":[4,6,1,2] }
        System.out.println("Object: \n" + obj.toString());

I see in your code that you are already using in the loop the Integer class which is an object-type wrapper of primitive type int . So the call jsonArray.add should work because num is an object and not a primitive type.

for (Integer num: nums) // Assume a List<Integer> nums
            jsonArray.add(num); 

Maybe you should try this code.

for(Integer num : nums)
   jsonArray.add(num.intValue());

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