How to save data with gson in a json file?

后端 未结 3 2189
野的像风
野的像风 2021-02-05 02:45

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

3条回答
  •  忘掉有多难
    2021-02-05 03:32

    Quick fix to your code:

    SqlSession session = MyBatisSqlSessionFactory.getSession();
    List users = session.selectList("dao.UserDao.findAll");
    try {
        JsonWriter writer = new JsonWriter(new FileWriter("C:\\file.json"));
        writer.beginObject();
        writer.name("data");
        writer.beginArray();
        for (User u : users) {
            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();
    }
    

    However, in the case that your User class looks like this:

    public class User {
        String id;
        String name;
    }
    

    Then you don't need to code the adapter as Gson is able to automatically generate the JSON code for a class that only has primitives (ints, Strings, etc.). So your code would look as @roy-shmuli but only if you omit the data and keep only the array as List can be completely generated without an adapter. The JSON code generated would look like this:

    [
        {"id":1, "name": "Mike"},
        {"id":2, "name": "Lucy"}
    ]
    

    Hope it helps to the beginners.

提交回复
热议问题