JSON-简单。追加到 JSON 数组

JSON-Simple. Append to a JSONArray

我正在使用 JSON-简单库来解析 Json 格式。如何将某些内容附加到 JSON 数组?例如考虑以下 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?

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

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

fiddle example

你可以试试这个:

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);
    }

这将满足您的两个要求。