'How to update a JSON array in a Java

I have a JSON file name abc.json Once I opened this file there is data like in square brackets.

[{
"1" : "xxx",
"20" : "ppp",
"25" : "hhh"
}]

Here in this keys are not known. I want to add new key-value pairs, update values according to some key-value and delete some fields. I have to use com.google.code library.



Solution 1:[1]

As said already in comments, there are some flaws in this architecture.

However, as a json object is basically a Map in java, you can use jackson lib to deserialize the json, add a value in the map and serialize it again with jackson. See the code below :

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.Map;


class ObjectMapperTest {


    @Test
    void test_json_array_of_map() throws JsonProcessingException {
        String jsonAsString = "[{\"1\":\"xxx\",\"20\":\"ppp\",\"25\":\"hhh\"}]";

        ObjectMapper objectMapper = new ObjectMapper();
        List<Map<String,String>> deserialized = objectMapper.readValue(jsonAsString, new TypeReference<>() {
        });
        deserialized.get(0).put("myNewKey", "myNewValue");

        System.out.println(objectMapper.writeValueAsString(deserialized));
    }

}

This gives you the following output :

[{"1":"xxx","20":"ppp","25":"hhh","myNewKey":"myNewValue"}]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stanislas Klukowski