[英]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 我的输出JSON需要为
{
"id" : "somestring",
"nums" : [44,31,87,11,34]
}
I'm using the javax.json
library with JSONObject
/ JsonArray
. 我在JSONObject
/ JsonArray
使用javax.json
库。 There is a List<Integer>
which comes in with the values for the 2nd field. 有一个List<Integer>
,其中包含第二个字段的值。 These aren't objects, these are plain numbers. 这些不是对象,而是纯数字。 I don't know how to get a JSONValue from an Integer. 我不知道如何从整数获取JSONValue。
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
createArrayBuilder
method will return JsonArrayBuilder
object, you should not do the explicit type casting. createArrayBuilder
方法将返回JsonArrayBuilder
对象,您不应执行显式类型转换。 So first create array builder and then add Integers
to it 因此,首先创建数组生成器,然后向其中添加Integers
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for (Integer num: nums) {
jsonArray.add(num);
}
Then finally call build
method that will build JsonArray
然后最后调用将构建JsonArray
build
方法
JsonArray array = jsonArray.build();
FINAL SOLUTION (thanks Deadpool ) 最终解决方案 (感谢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 . 我在您的代码中看到,您已经在循环中使用了Integer类,它是原始类型int的对象类型包装器。 So the call jsonArray.add should work because num is an object and not a primitive type. 所以调用jsonArray.add应该可以工作,因为num是一个对象而不是原始类型。
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.