user2200561 user2200561 - 1 month ago 5
Java Question

How to read the JSONArray from json file and append new json array elements and again write it to the same json file using java

I have json array in the below shown format in my json file

[
{"cityid":"1","cityname":"aaaa","zipcode":"434343","district":"ababab","state":"kkkkkkk"},
{"cityid":"2","cityname":"bbbb","zipcode":"434355","district":"acaaca","state":"mmmmmmm"}
]


Now I want to add another array into this through java and my json file should look like

[
{"cityid":"1","cityname":"aaaa","zipcode":"434343","district":"ababab","state":"kkkkkkk"},
{"cityid":"2","cityname":"bbbb","zipcode":"434355","district":"acaaca","state":"mmmmmmm"},
{"cityid":"3","cityname":"cccc","zipcode":"656565","district":"uyuyuu","state":"ttttttt"}
]


I have tried many examples googling around but cud not get any satisfactory answer. Please Help

Answer

You can get array from file, parse it to List, add Java object to it, parse all list back to json array and rewrite all file.

Another approach is to use RandomAccessFile.class First set file-pointer to end of file, read file from end, and when randomAccessFile.read==']', append , and your json String.

There is you can find code example of second approach: Append JSON element to JSON array in file using Java