mak_doni mak_doni - 1 month ago 10
Java Question

How to save data with gson in a json file?

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();

Answer

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

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

Example:

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