List转换成json格式字符串,json格式字符串转换成list

时间:2023-11-25 17:12:26

一、List转换成json字符串

这个比较简单,导入gson-x.x.jar,

List<User> users = new ArrayList<User>();
Gson gson = new Gson(),
String json = gson.toJson(users)

返回的就是json格式字符串

[{"id":2,"userName":"liuwenlei","isLogin":2},{"id":3,"userName":"liuxinglei","isLogin":2}]

二、json字符串转换成List

需要导入的jar包有:

json-lib-2.4-jdk15.jar

commons-beanutils-1.8.3.jar

ezmorph-1.0.6.jar

String jsonString = "[{\"id\":2,\"userName\":\"liuwenlei\",\"isLogin\":2},{\"id\":3,\"userName\":\"liuxinglei\",\"isLogin\":2}]";
        JSONArray gsonarr = JSONArray.fromObject(jsonString);
        List<User> users = JSONArray.toList(gsonarr, User.class);
        System.out.println(users);

输出的结果为

[User [id=2, userName=liuwenlei, isLogin=2], User [id=3, userName=liuxinglei, isLogin=2]]