0

我正在使用 JSON-simple 库来解析 Json 格式。如何将某些内容附加到 JSONArray?例如,考虑以下 json

{
    "a": "b"
    "features": [{/*some complex object*/}, {/*some complex object*/}]
}

我需要在features. 我正在尝试创建这样的函数:-

public void appendToList(JSONObject jsonObj, JSONObject toBeAppended){

    JSONArray arr = (JSONArray)jsonObj.get("features");

    //1) append the new feature
    //2) update the jsonObj
}

如何实现上述代码中的第 1 步和第 2 步?

4

2 回答 2

3

你可以试试这个:

public static void main(String[] args) throws ParseException {

    String jsonString = "{\"a\": \"b\",\"features\": [{\"feature1\": \"value1\"}, {\"feature2\": \"value2\"}]}";
    JSONParser parser = new JSONParser();
    JSONObject jsonObj = (JSONObject) parser.parse(jsonString);

    JSONObject newJSON = new JSONObject();
    newJSON.put("feature3", "value3");

    appendToList(jsonObj, newJSON);

    System.out.println(jsonObj);
    }


private static void appendToList(JSONObject jsonObj, JSONObject toBeAppended) {

        JSONArray arr = (JSONArray) jsonObj.get("features");        
        arr.add(toBeAppended);
    }

这将满足您的两个要求。

于 2015-05-04T10:52:22.643 回答
-1

通过: 获取数组jsonObj["features"],然后您可以通过将其分配为数组中的最后一个元素来添加新项目(jsonObj["features"].length是添加新元素的下一个空闲位置)

jsonObj["features"][jsonObj["features"].length] = toBeAppended;

小提琴示例

于 2015-05-04T10:46:05.017 回答