我需要一些帮助将新数组附加到现有文件中。我有一个像这样的 JSON 文件:
[
{
"name": "any",
"address": {
"street": "xxxx",
"number": 1
},
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e99d8c9a9d8ca98e84888085c78a8684" rel="noreferrer noopener nofollow">[email protected]</a>"
}
]
我想插入新数组,所以我的文件将如下所示:
[
{
"name": "any",
"address": {
"street": "xxxx",
"number": 1
},
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c48594f487c5b515d5550125f5351" rel="noreferrer noopener nofollow">[email protected]</a>"
},
{
"name": "any2",
"address": {
"street": "yyyyy",
"number": 2
},
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="483c2d3b3c7a082f25292124662b2725" rel="noreferrer noopener nofollow">[email protected]</a>"
}
]
这是我的代码:
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();
}
那么,最好的方法是什么? 提前致谢。
最佳答案
Gson 与 Pojos 结合时确实很出色,所以我的建议是使用映射的 pojos。考虑下面两个类。
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...
}
读取 JSON 并添加新联系人并将其转换回 JSON,它也可以无缝地用于其他方式。同样,您可以使用这种方法来解决许多用例。通过从文件读取或使用类似的方式传递 json 数组字符串,之后
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);
有像this one这样的工具从 JSON 创建 pojo。
关于java - Gson 将新对象数组附加到现有 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47111676/