如何在json文件中使用gson保存数据? [英] How to save data with gson in a json file?

查看:869
本文介绍了如何在json文件中使用gson保存数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Web应用程序中,我成功使用mybatis在html表中显示数据。现在我想在一个json文件中保存Mysql表的记录并创建一个用户数组,我用过Gson,问题是只保存在文件中的一条记录。谢谢。

结果在 file.json

In my web application I succeed in displaying data in html table using mybatis. Now I want to save the records of the Mysql table in a json file and create an array of users, I used Gson, the problem is that just one record saved in the file. Thanks.
Here the result in file.json:

{"data":
 [
 {"id":2,"Name":"Mike"}
 ]
}

servlet.java

SqlSession session = MyBatisSqlSessionFactory.getSession();
List<User> users = session.selectList("dao.UserDao.findAll");
for (User u : users) {
    Gson gson = new Gson();
    try {
        JsonWriter  writer = new JsonWriter(new FileWriter("C:\\file.json"));
        writer.beginObject();
        writer.name("data");
        writer.beginArray();
        writer.beginObject();
        writer.name("id").value(t.getId());
        writer.name("name").value(t.getNom());
        writer.endObject();
        writer.endArray();
        writer.endObject();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

session.close();


推荐答案

您在同一档案中写下所有用户 C:\\ file.json 所以只保存了循环的最后一次迭代。

You write all the users in same file C:\\file.json so just the last iteration of the loop saved.

你可以转换对象列出< User> 进入json并写一次(无需循环)

You can convert the object List<User> into json and write it once (no needed loop)

示例:

try (Writer writer = new FileWriter("Output.json")) {
    Gson gson = new GsonBuilder().create();
    gson.toJson(users, writer);
}

这篇关于如何在json文件中使用gson保存数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆