fastJson泛型如何转换
fastjson
FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
项目地址:https://gitcode.com/gh_mirrors/fastj/fastjson
免费下载资源
·
引子
现在负责的业务 和 json 打交道比较多, 最近使用fastJson框架 json串转成泛型对象遇到了一个异常 :
java.lang.ClassCastException
还原下场景 :
模型Result<T>
public class Result<T> { private String msg; private List<T> module; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<T> getModule() { return module; } public void setModule(List<T> module) { this.module = module; } }
为什么要使用泛型, 可以理解泛型可以接受任意类型, 有些代码是公用的, 如结果集, 不可能为每个具体结果定义一个模型, 比如 Result<User>、Result<Item>等。
public class User { private Long user_id; private String user_name; public User() { } public User(Long userId, String name) { this.user_id = userId; this.user_name = name; } public Long getUser_id() { return user_id; } public void setUser_id(Long user_id) { this.user_id = user_id; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } }
下面直接看下泛型的转换
public static void main(String[] args) { Result<User> r = new Result<User>(); r.setMsg("msg"); List<User> users = new ArrayList<>(); users.add(new User(1L, "hehe")); users.add(new User(2L, "haha")); r.setModule(users); String js = JSON.toJSONString(r); System.out.println(js); Result<User> obj = (Result<User>)JSON.parseObject(js, Result.class); User user = obj.getModule().get(0); System.out.println(user); }
结果 :
{"module":[{"user_id":1,"user_name":"hehe"},{"user_id":2,"user_name":"haha"}],"msg":"msg"}
Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to com.yuanmeng.json.User
at com.yuanmeng.json.fanxing.Client.main(Client.java:32)
采用fastjson框架的 TypeReference 即可将json串转成定义好的泛型对象
Result<User> obj = (Result<User>) JSON.parseObject(js, new TypeReference<Result<User>>(){});
GitHub 加速计划 / fastj / fastjson
25.69 K
6.51 K
下载
FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
最近提交(Master分支:3 个月前 )
c942c834 - 1 年前
5bc4709b - 1 年前
更多推荐
已为社区贡献1条内容
所有评论(0)