2

i need some help appending new arrays into a existing file. I have a JSON file like this:

[
  {
    "name": "any",
    "address": {
      "street": "xxxx",
      "number": 1
    },
    "email": "[email protected]"
  }
]

I want to insert new array, so my file will be like this:

[
      {
        "name": "any",
        "address": {
          "street": "xxxx",
          "number": 1
        },
        "email": "[email protected]"
      },
      {
        "name": "any2",
        "address": {
          "street": "yyyyy",
          "number": 2
        },
        "email": "[email protected]"
      }
]

Here's my code:

Gson gson = new GsonBuilder().setPrettyPrinting().create();    
ArrayList<Person> ps = new ArrayList<Person>();

//  .... reading entries...

ps.add(new Person(name, address, email));
String JsonPerson = gson.toJson(ps);

File f = new File("jsonfile");
if (f.exists() && !f.isDirectory()) { 
    JsonReader jsonfile = new JsonReader(new FileReader("jsonfile"));
    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(jsonfile);
    //here goes the new entry?

    try (FileWriter file = new FileWriter("pessoas.json")) {
        file.write(JsonPessoa);
        file.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

So, what's the best way to do this? Thanks in advance.

1 Answer 1

3

Gson really shines when combined with Pojos, so my suggestion would be use of mapped pojos. Consider below two classes.

public class Contact {

    @SerializedName("address")
    private Address mAddress;
    @SerializedName("email")
    private String mEmail;
    @SerializedName("name")
    private String mName;

    // getters and setters...

}

public class Address {

    @SerializedName("number")
    private Long mNumber;
    @SerializedName("street")
    private String mStreet;

    // getters and setters...

}

Read JSON and add new contact and convert it back to JSON, It also works for other way around seamlessly. Similarly you can use this approach for solve many use cases. Pass json array string by reading from file or using similar way, after

Gson gson = new Gson();

List<Contact> contacts = gson.fromJson("JSON STRING", new TypeToken<List<Contact>>() {}.getType());

Contact newContact = new Contact();
// set properties
contacts.add(newContact);

String json = gson.toJson(contacts);

There are tools like this one to create pojos from JSON.

Sign up to request clarification or add additional context in comments.

1 Comment

What if my json file is a couple megabytes? I don't want to slow the program by re-writing the whole thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.