我有json {"name": "John", "tests":["apple"]}
。在我的Java代码中,我想通过gson更新此json - 将字符串字段添加到json数组并保存到文件以获得此json - {"name": "John", "tests":["apple", "pinapple"]}
。那有怎样的方法呢?我的json的Java类看起来像这样:
public class Test{
private String name;
private List<String> tests;
// Getters/Setters
}
在java中读取json:
Gson gson = new Gson();
try (Reader reader = new FileReader("D:\\file.json")) {
Test js = gson.fromJson(reader, Test.class);
System.out.println(js.getName());
} catch (IOException e) {
e.printStackTrace();
}
这样做我的新json文件为空:
Gson gson = new Gson();
try (Reader reader = new FileReader("D:\\file.json")) {
Test test = gson.fromJson(reader, Test.class);
System.out.println(test.getName());
test.getTests().add("pinapple");
String newJson = gson.toJson(test);
System.out.println(newJson);
gson.toJson(test, new FileWriter("D:\\file.json"));
} catch (IOException e) {
e.printStackTrace();
}
答案 0 :(得分:0)
Test test = gson.fromJson(reader, Test.class);
获得Test
对象后:
test.getTests().add("pineapple");
现在你的数组中有pineapple
。您可以创建JSON字符串:
String newJson = gson.toJson(test);
System.out.println(newJson);
或将其写回同一个文件
gson.toJson(test, new FileWriter("D:\\file.json"));
编辑:整个代码
String fileName = "D:\\file.json";
Gson gson = new Gson();
Test test = null;
try (Reader reader = new FileReader(fileName)) {
test = gson.fromJson(reader, Test.class);
} catch (IOException e) {
e.printStackTrace();
}
test.getTests().add("pineapple");
String newJson = gson.toJson(test);
System.out.println(newJson);
try (Writer writer = new FileWriter(fileName)) {
gson.toJson(test, writer);
}