Add element to array Json with Gson

0

This is my Json file:

[{"nombre":"Activo","valor": 8500},{"nombre":"Pasivo","valor":500000}]

And I want to add another object to the last position of that array using Gson, I try the following:

public void add(Cuenta cuenta) throws IOException{

    String cuentaSerializada = myGson.toJson(cuenta);
    this.writeJson(cuentaSerializada);
}

private void writeJson(String cuentaSerialized) throws IOException{
    this.bufferToWrite = new BufferedWriter(new FileWriter(this.filePath, true));
    this.bufferToWrite.append(cuentaSerialized);
    this.bufferToWrite.close();
}

But the only thing it does is add an object outside the array:

 [{"nombre":"Activo","valor": 8500},{"nombre":"Pasivo","valor":500000}]{"nombre":"Patrimonio","valor":152000}

I use Java in Eclipse

    
asked by Jack Manson 28.04.2017 в 05:32
source

1 answer

1

What you are doing is an append to the file, so it is logical that after the last character], your String is attached, thus being outside the array.

You should do a JsonArray of your file, then a JsonElement with your new entry, put the Element in the Array, and then convert the Array into Json using Gson.

    
answered by 28.04.2017 в 18:23