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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

this does not satisfy the method signature i have provided above.
Instead of creating a new JSONObject instance, just add the 2nd argument in the method to the arr using the put call.
this is not what I meant. Just assume that I don't have any information what is inside the "complex object" I have mentioned above
The information of complex object is not needed as you have to add a new entry in JSONArray, As shown above you can add it using add method.
does adding it to the array update the original jsonObj?
|
-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

3 Comments

OP is asking for an example in json-simple, not javascript.
While this source code may provide an answer, a few words of explanation would benefit current and future readers.
@TheThom I've added some explanation, thanks for your comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.