Search code examples
javajsonjson-simple

JSON-Simple. Append to a JSONArray


I am using the JSON-simple library to parse the Json format. How can I append something to a JSONArray? For e.g. consider the following json

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

I need to append a new entry in the features. I am trying to create a function like this:-

public void appendToList(JSONObject jsonObj, JSONObject toBeAppended){

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

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

How to achieve steps 1 & 2 in the above code?


Solution

  • You can try this:

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

    This will fulfill your both requirements.