簡體   English   中英

javax.json:從列表構建JSONArray <Integer> 並將其添加到JSONObject

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM