您的位置:首页 > Web前端 > JavaScript

利用Jackson框架将json字符串转换成泛型List

2017-11-01 11:25 495 查看
Jackson处理一般的JavaBean和Json之间的转换只要使用ObjectMapper 对象的readValue和writeValueAsString两个方法就能实现。但是如果要转换复杂类型Collection如 List<YourBean>,那么就需要先反序列化复杂类型 为泛型的Collection Type。

如果是ArrayList<YourBean>那么使用ObjectMapper 的getTypeFactory().constructParametricType(collectionClass, elementClasses);

如果是HashMap<String,YourBean>那么 ObjectMapper 的getTypeFactory().constructParametricType(HashMap.class,String.class, YourBean.class);
public static void main(String[] args) throws Exception{
ObjectMapper mapper = new ObjectMapper();
JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, YourBean.class);
List<YourBean> lst =  (List<YourBean>)mapper.readValue(jsonString, javaType);
}


参考:http://www.cnblogs.com/quanyongan/archive/2013/04/16/3024993.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: