深度解析json转化、Jackson使用
json 格式转化使用jackson更加方便一些。
》
》
1、存在3种常见的场景、
- 简单类型
- List 集合
- Map 集合
针对json 和对象之间的转换,jackson 提供了 2 个通用的方法、public String writeValueAsString 和public T readValue(String content, TypeReference valueTypeRef) 分别用来序列化和反序列化、
创建单元测试如下、
/** * @auther SyntacticSugar * @data 2018/12/3 0003上午 9:20 */
public class JackSion {
@Test
public void test() throws IOException {
User user=null;
String json=null;
ObjectMapper mapper = new ObjectMapper();
//序列化、反序列化
json = mapper.writeValueAsString(user);
user = mapper.readValue(json, new TypeReference<User>() {
});
// 对list 集合来讲、序列化反序列化/使用流Arrays.asList转化为list集合
json = mapper.writeValueAsString(Arrays.asList(user,user,user,user));
List<User> users = mapper.readValue(json, new TypeReference<List<User>>() {
});
// 对map 集合来讲、序列化反序列化
HashMap<String, List<User>> map = new HashMap<>();
json = mapper.writeValueAsString(map);
Object o = mapper.readValue(json, new TypeReference<HashMap<String, List<User>>>() {
});
}
}
测一下、
还没有评论,来说两句吧...