Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append JSON element to JSON array in file using Java

Tags:

java

json

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?

like image 736
vaibhav.g Avatar asked Oct 08 '14 05:10

vaibhav.g


People also ask

How do you add a JSON object to an array in Java?

We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.

How do I add a JSON string to an existing JSON file?

In the initial step, we can read a JSON file and parsing to a Java object then need to typecast the Java object to a JSonObject and parsing to a JsonArray. Then iterating this JSON array to print the JsonElement. We can create a JsonWriter class to write a JSON encoded value to a stream, one token at a time.


1 Answers

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();
like image 180
Max Gontijo de Oliveira Avatar answered Nov 12 '22 04:11

Max Gontijo de Oliveira