GSON将java对象添加到json数组

时间:2018-03-29 20:56:47

标签: java json gson

我有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();
    }

1 个答案:

答案 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);
}