Gson append new object array to existing JSON file

做~自己de王妃 提交于 2021-01-04 09:20:25

问题


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": "teste@gmail.com"
  }
]

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

[
      {
        "name": "any",
        "address": {
          "street": "xxxx",
          "number": 1
        },
        "email": "test@gmail.com"
      },
      {
        "name": "any2",
        "address": {
          "street": "yyyyy",
          "number": 2
        },
        "email": "test2@gmail.com"
      }
]

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:


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.



来源:https://stackoverflow.com/questions/47111676/gson-append-new-object-array-to-existing-json-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!