1
[
    {
        "key":"key1",
        "value":"key one value",
        "description":""
    },
    {
        "key":"key2",
        "value":"key two value",
        "description":""
    },
    {
        "key":"key3",
        "value":"key three value",
        "description":""
    },
    {
        "key":"key4",
        "value":"key four value",
        "description":""
    },
    {
        "key":"key5",
        "value":"key five value",
        "description":""
    }   
]

This above is my an example json file I'm working with, I'm putting it into an JsonArray like this

BufferedReader reader = Files.newBufferedReader(file,
                Charset.defaultCharset());
JsonReader jsonReader = Json.createReader(reader);
JsonArray array = jsonReader.readArray();

And My issue is I want to access the JsonArray and change the value part of each json element but is unable to do this. the collection doesn't seem to offer anyways to replace values of any json element. Do you know anyways I could achieve what I'm set to to do?? PS: also open to suggestions on using an alternative collection, but please educate me on why should I choose said collection.

1 Answer 1

1

Since you did not mention which JSON library you are using, you can use element method if you are using json-lib to replace an element

public JSONArray element(int index,
                         Object value)

If you want to update a specific attribute of the JSONObject element, you can try something like below

array.getJSONObject(0).put("key","new key value")

Please note that I have used hard coded value 0 for demonstration purposes.

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

4 Comments

Okay, in that case JSONArray is immutable. You will have to read each individual JSONObject from the array, and convert it to JSONObjectBuilder somehow, and then package them in a new array using JSONArrayBuilder. Is it possible to use some other JSON library like Jackson which allows better binding to Java POJOs?
I could some other JSON library, but there seem to be alot of them to choose from and i have no clue which one to go for. Can you give me an recommandation on which one I should use and to acomplish this the simpliest way opssible?
adopted JSON.simple, resolved my question, thank you for the help!
Nice. There are many JSON frameworks, its not easy to recommend one. Best option is to pick one that works for your current needs and look at others only if develop new needs that are not met by your current framework

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.