java - How to save data with gson in a json file? -


in web application succeed in displaying data in html table using mybatis. want save records of mysql table in json file , create array of users, used gson, problem 1 record saved in file. thanks.
here result in file.json:

{"data":  [  {"id":2,"name":"mike"}  ] } 

servlet.java

sqlsession session = mybatissqlsessionfactory.getsession(); list<user> users = session.selectlist("dao.userdao.findall"); (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(); 

you write users in same file c:\\file.json last iteration of loop saved.

you can convert object list<user> json , write once (no needed loop)

example:

try (writer writer = new filewriter("output.json")) {     gson gson = new gsonbuilder().create();     gson.tojson(users, writer); } 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -