介绍几款常用的Json转换工具
作者:互联网
一、Jackson
1、引入依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.10.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.10.0</version> </dependency>
2、使用示例
ObjectMapper mapper = new ObjectMapper();
//(序列化)对象转json字符串 String userStr = mapper.writeValueAsString(user); //(反序列化)json字符串转对象 User user= mapper.readValue(userStr,User.class); //List的序列化与反序列化 List<User> userlist = new ArrayList<>(); ... ... userlist.add(user); userlist.add(user2); //转字符串用法一样 String userListStr = mapper.writeValueAsString(userlist); //转对象使用TypeReference,否则报LinkedHashMap类型转换错误 List<User> userList = mapper.readValue(userListStr,new TypeReference<List<User>>(){}); System.out.println(userList.get(0).getUserName());
标签:mapper,转换,core,userlist,Json,new,jackson,序列化,几款 来源: https://www.cnblogs.com/javasl/p/13025872.html