Append JSON element to JSON array in file using Java -
Append JSON element to JSON array in file using Java -
currently have next json array object in file(name.json).
[{ "name":"ray", "value":"1" }, ]
now want add together 1 more element in json array in file using java. this:
[{ "name":"ray", "value":"1" }, { "name":"john", "value":"2" } ]
one way read entire array file, append element array , write json file in java. not optimum way task. can suggest other way this?
try this:
1 - create randomaccessfile object read/write permissions ("rw");
randomaccessfile randomaccessfile = new randomaccessfile("/path/to/file.json", "rw");
2 - set file cursor position of char "]"
long pos = randomaccessfile.length(); while (randomaccessfile.length() > 0) { pos--; randomaccessfile.seek(pos); if (randomaccessfile.readbyte() == ']') { randomaccessfile.seek(pos); break; } }
3 - write comma (if not first element), new json element , char "]"
string jsonelement = "{ ... }"; randomaccessfile.writebytes("," + jsonelement + "]");
4 - close file
randomaccessfile.close();
java json
Comments
Post a Comment