'how to update json array in java with existing json array value using java. Value are not updating in external json file

JSON file: [
{
"name":"John", "city":"Berlin", "job":"Teacher" }, {
"name":"Mark", "city":"Oslo", "job":"Doctor" } ]

JSONParser parser = new JSONParser(); JSONArray a = (JSONArray) parser.parse(new FileReader("F:\file.json"));

    for (Object o : a) {
        JSONObject person = (JSONObject) o;

        String name = (String) person.get("name");
        
        if (name.equalsIgnoreCase("john")) {
            String name1 = (String) person.get("name");
            System.out.println("name1" + name1);

            String city1 = (String) person.get("city");
            System.out.println("city1" + city1);

            String job1 = (String) person.get("job");
            System.out.println("job1" + job1);  
            
            person.put("city", "BLR");
            String city2 = (String) person.get("city");
            System.out.println("city2" + city2);
        }
    }

Value are not updating in Json external file



Solution 1:[1]

JSONObject is a represent of json that does not link to originally file. To rewrite file you need to change values in person and write it to file.

person.put("city", "BLR");
String jsonString = person.toString();
// write jsonString to file

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 Egor