0

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?

ishan3243
  • 1,870
  • 4
  • 30
  • 49

2 Answers2

4

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.

Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
-1

Getting the array by: jsonObj["features"], then you can add new item by assign it as the last element in the array ( jsonObj["features"].length is the next free place to add new element)

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

fiddle example

ItayB
  • 10,377
  • 9
  • 50
  • 77