[英]javax.json - Build JsonObject with arraylist and one separated attribute
[英]javax.json: Build a JSONArray from a List<Integer> and add it to a JSONObject
簡單的任務,但我找不到方法。
我的輸出JSON需要為
{
"id" : "somestring",
"nums" : [44,31,87,11,34]
}
我在JSONObject
/ JsonArray
使用javax.json
庫。 有一個List<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
方法將返回JsonArrayBuilder
對象,您不應執行顯式類型轉換。 因此,首先創建數組生成器,然后向其中添加Integers
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for (Integer num: nums) {
jsonArray.add(num);
}
然后最后調用將構建JsonArray
build
方法
JsonArray array = jsonArray.build();
最終解決方案 (感謝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());
我在您的代碼中看到,您已經在循環中使用了Integer類,它是原始類型int的對象類型包裝器。 所以調用jsonArray.add應該可以工作,因為num是一個對象而不是原始類型。
for (Integer num: nums) // Assume a List<Integer> nums
jsonArray.add(num);
也許您應該嘗試使用此代碼。
for(Integer num : nums)
jsonArray.add(num.intValue());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.