Search code examples
javajsoniogsonapache-commons

Read From JSON File and after adding a property to that object write back to it


I have an empty json file in my java project with only json object bracket:- that is

a.json

{}

i want to read from it and after adding a key value write back to it, that is:-

{"a":"a"}

Is there any Json Library i can use to do so.

I don't wanna use simple FileReaders and FileWriters in java to read and write.


Solution

  • There are several libraries for this task.

    One could be Jettison https://mvnrepository.com/artifact/org.codehaus.jettison/jettison

    Path filePath = <your-file-path>;
    String json = new String(Files.readAllBytes(filePath));
    JSONObject jsonObject = new JSONObject(json);
    jsonObject.put("a", "a");
    Files.write(filePath, jsonObject.toString().getBytes());