Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace value in json file

Tags:

java

json

I have a JSON file i.e test.json.

{
  "Added": {
    "type": "K",
    "newmem": {
      "IDNew": {
        "id": "777709",
        "type": "LOP"
      },
      "birthDate": "2000-12-09"
    },
    "code": "",
    "newest": {
      "curlNew": "",
      "addedForNew": ""
    }
  }
}

I tried the following code :

File file = new File("test.json");
JSONParser parser = new JSONParser();

JSONObject data =  (JSONObject) parser.parse(
   new FileReader(file.getAbsolutePath()
));//path to the JSON file.
System.out.println(data.toString());

JSONObject jObject  = new JSONObject();
jObject.put("id","12345678");
System.out.println(jObject);

Result getting :-

{
  "Added": {
    "type": "K",
    "newmem": {
      "IDNew": {
        "id": "777709",
        "type": "LOP"
      },
      "birthDate": "2000-12-09"
    },
    "code": "",
    "newest": {
      "curlNew": "",
      "addedForNew": ""
    }
  }
}{
"id":"12345678"
}

Value id: "777709" is not getting updating to id:"12345678" but it's adding at last. Please help me to and tell me how to replace the id value.

like image 594
Little bird Avatar asked Nov 21 '18 09:11

Little bird


People also ask

How do you change a value in a JSON file?

First you would need to convert it to a JavaScript Object. Once it is an Object, then you can just use dot notation into the object to change the values that you want. Lastly, you would convert that JavaScript Object back into a JSON string.


3 Answers

You can try this with simple json library(library) . I am separately printed all object for understanding. AS you declare Id object inside two more object, so firstly you have to get this object then get your desire object IDNew. Then put new id value in id field.

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class Main {

    private static final String filePath = "E:\\project-test\\scloud\\test\\src\\main\\resources\\test";

    public static void main(String[] args) {

        try {
            // read the json file
            FileReader reader = new FileReader(filePath);

            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

            System.out.println(jsonObject);


            JSONObject addedObj = (JSONObject) jsonObject.get("Added");
            System.out.println("Added is: " + addedObj);

            JSONObject newmemObject =(JSONObject) addedObj.get("newmem");
            System.out.println("newmemObject is: " + newmemObject);

            JSONObject idNewObj =(JSONObject) newmemObject.get("IDNew");
            System.out.println("IdNewObj is: " + idNewObj);

            long id =Long.valueOf((String) idNewObj.get("id"));
            System.out.println(id);


            idNewObj.put("id",809809809);

            System.out.println(jsonObject);

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ParseException ex) {
            ex.printStackTrace();
        } catch (NullPointerException ex) {
            ex.printStackTrace();
        }

    }

}

Or for simplicity you can use this

    FileReader reader = new FileReader(filePath);
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
    System.out.println(jsonObject);

    JSONObject idObj = (
       (JSONObject) (
             (JSONObject) (
                (JSONObject)
                   jsonObject.get("Added")
             ).get("newmem")
       ).get("IDNew")
    );

    idObj.put("id", 98009809);
    System.out.println("After ID value updated : "+jsonObject);
like image 193
flopcoder Avatar answered Nov 09 '22 05:11

flopcoder


You can update a nested element in a JSONObject using the simple-json java lib as follows:

JSONObject added = (JSONObject) data.get("Added");
JSONObject newmem = (JSONObject) added.get("newmem");
JSONObject idNew = (JSONObject) newmem.get("IDNew");
idNew.put("id","12345678");
System.out.println(data);
like image 20
taygetos Avatar answered Nov 09 '22 05:11

taygetos


One more solution using different library json-path:

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

import static org.assertj.core.api.Assertions.assertThat;

    @Test
    public void exampleToReplaceSingleElement_jsonTakenFromFile() throws IOException {
        String expectedId = "12345678";
        String expectedJson = "{\n" +
                "  \"Added\": {\n" +
                "    \"type\": \"K\",\n" +
                "    \"newmem\": {\n" +
                "      \"IDNew\": {\n" +
                "        \"id\": \"12345678\",\n" +
                "        \"type\": \"LOP\"\n" +
                "      },\n" +
                "      \"birthDate\": \"2000-12-09\"\n" +
                "    },\n" +
                "    \"code\": \"\",\n" +
                "    \"newest\": {\n" +
                "      \"curlNew\": \"\",\n" +
                "      \"addedForNew\": \"\"\n" +
                "    }\n" +
                "  }\n" +
                "}";

        Configuration configuration = Configuration
                .builder()
                .options(Option.SUPPRESS_EXCEPTIONS)
                .build();
        File json = new File("src/test/resources/test.json");
        System.out.println(json.getAbsolutePath());
        DocumentContext parsed = JsonPath.using(configuration).parse(json);

        parsed.set("$.Added.newmem.IDNew.id", expectedId);
        String actual = parsed.jsonString();

        log.info("After ID value updated: {}", actual);
        assertThat(actual).isEqualToIgnoringWhitespace(expectedJson);
    }

Examples also accessible on get test exampleToReplaceSingleElement() or test exampleToReplaceSingleElement_jsonTakenFromFile().

like image 20
Sergii Avatar answered Nov 09 '22 05:11

Sergii