简体   繁体   中英

Append JSON element to JSON array in file using Java

Currently I have the following json array object in file(name.json).

[{
  "name":"ray",
  "value":"1"
 },
]

Now I want to add one more element in this Json array in the file using java. Something like this:

[{
  "name":"ray",
  "value":"1"
 },
 {
  "name":"john",
  "value":"2"
 }
]

One way could be to read the entire array from the file, append an element to that array and write it back to json file in java. But this is definitely not the optimum way to do this task. Can anyone suggest any other way to this?

Try this:

1 - create a RandomAccessFile object with read/write permissions ("rw");

RandomAccessFile randomAccessFile = new RandomAccessFile("/path/to/file.json", "rw");

2 - set the file cursor to the position of the char "]"

long pos = randomAccessFile.length();
while (randomAccessFile.length() > 0) {
    pos--;
    randomAccessFile.seek(pos);
    if (randomAccessFile.readByte() == ']') {
        randomAccessFile.seek(pos);
        break;
    }
}

3 - write a comma (if is not the first element), the new json element and the char "]"

String jsonElement = "{ ... }";
randomAccessFile.writeBytes("," + jsonElement + "]");

4 - close the file

randomAccessFile.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM