深度解析json转化、Jackson使用

た 入场券 2022-04-12 11:25 333阅读 0赞

json 格式转化使用jackson更加方便一些。

1、存在3种常见的场景、
  • 简单类型
  • List 集合
  • Map 集合

针对json 和对象之间的转换,jackson 提供了 2 个通用的方法、public String writeValueAsString 和public T readValue(String content, TypeReference valueTypeRef) 分别用来序列化和反序列化、
创建单元测试如下、

  1. /** * @auther SyntacticSugar * @data 2018/12/3 0003上午 9:20 */
  2. public class JackSion {
  3. @Test
  4. public void test() throws IOException {
  5. User user=null;
  6. String json=null;
  7. ObjectMapper mapper = new ObjectMapper();
  8. //序列化、反序列化
  9. json = mapper.writeValueAsString(user);
  10. user = mapper.readValue(json, new TypeReference<User>() {
  11. });
  12. // 对list 集合来讲、序列化反序列化/使用流Arrays.asList转化为list集合
  13. json = mapper.writeValueAsString(Arrays.asList(user,user,user,user));
  14. List<User> users = mapper.readValue(json, new TypeReference<List<User>>() {
  15. });
  16. // 对map 集合来讲、序列化反序列化
  17. HashMap<String, List<User>> map = new HashMap<>();
  18. json = mapper.writeValueAsString(map);
  19. Object o = mapper.readValue(json, new TypeReference<HashMap<String, List<User>>>() {
  20. });
  21. }
  22. }

测一下、
1

发表评论

表情:
评论列表 (有 0 条评论,333人围观)

还没有评论,来说两句吧...

相关阅读