使用java将JSON对象添加到现有JSON数组中

时间:2017-11-21 12:13:22

标签: java json

这是我的JSON,我有一个字符串" additionalThirdParty"

{
    "header": null,
    "object": {
        "ASSETS": {
            "productDetails": [{
                "productId": "PT_230",
                "productThirdPartyDetails": [{
                    "thirdPartyId": "TH12",
                    "Location": "France",
                    "addtionalInfo": []
                }]
            }]
        }
    }
}

现在我的要求是在" productThirdPartyDetails"中添加一个额外的JSON对象。阵列。

新的JSON对象将是

{
    "thirdPartyId": "TH11",
    "Location": "Belgium",
    "addtionalInfo": []
}

所以最终的对象应该是

{
    "header": null,
    "object": {
        "ASSETS": {
            "productDetails": [{
                "productId": "PT_230",
                "productThirdPartyDetails": [{
                        "thirdPartyId": "TH12",
                        "Location": "France",
                        "addtionalInfo": []
                    },
                    {
                        "thirdPartyId": "TH11",
                        "Location": "Belgium",
                        "addtionalInfo": []
                    }
                ]
            }]
        }
    }
}

我尝试添加如下内容。

将此字符串转换为JSON格式为

    JSONObject obj = new JSONObject(additionalThirdParty);

    Iterator<?> keys = obj.keys();

    while (keys.hasNext()) {
        JSONObject assetsObj = obj.getJSONObject("ASSETS");
        Iterator<?> assetKeys = assetsObj.keys();
        while (assetKeys.hasNext()) {
            JSONArray productDetails = assetsObj.getJSONArray("productDetails");
            logger.info("productDetails=" + productDetails);
        }
    }

它抛出了org.json.JSONException:找不到JSONObject [&#34; ASSETS&#34;]。

有关如何将新对象添加到该数组中的任何想法

2 个答案:

答案 0 :(得分:1)

为了达到你想要的效果,你必须正确地接触 productThirdPartyDetails ,如下所示,然后你必须确定获取需要添加的JSONObject的方式,我已经硬编码了通过一种方法获得该对象更好。

JSONObject obj = new JSONObject(additionalThirdParty);


        JSONObject objtobeadded =  new JSONObject();
        objtobeadded.put("thirdPartyId", "TH11");
        objtobeadded.put("Location", "Belgium");
        objtobeadded.put("addtionalInfo", new JSONArray());

        JSONObject assetsObj = obj.getJSONObject("object").getJSONObject("ASSETS");

        JSONArray prodDetailsArr = assetsObj.getJSONArray("productDetails");

        for(int i=0;i<prodDetailsArr.length();i++){            
            JSONArray arr = prodDetailsArr.getJSONObject(i).getJSONArray("productThirdPartyDetails");
            arr.put(objtobeadded);
        }
        System.out.println(obj.toString());

答案 1 :(得分:1)

JSONObject assetsObj = obj.getJSONObject("ASSETS"); here the ASSETS is in under object,

所以你应该写obj.getJSONObject("object").getJSONObject("ASSETS");来获得ASSETS对象。