Reputation: 759
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?
Upvotes: 8
Views: 2480
Reputation: 31
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();
Upvotes: 2