首先要知道三者的互转关系,可以先将JSON理解成是String类型。这篇博文主要是记录阿里巴巴的JSONObject的两个方法。toJSONString()以及parseObject()方法。顺便巩固Map与实体对象的转换技巧。
引入依赖
| |
| |
| <dependency> |
| <groupId>com.alibaba.fastjson2</groupId> |
| <artifactId>fastjson2</artifactId> |
| <version>2.0.12</version> |
| </dependency> |
| <dependency> |
| <groupId>com.alibaba</groupId> |
| <artifactId>fastjson</artifactId> |
| <version>1.2.83</version> |
| </dependency> |
| |
| <dependency> |
| <groupId>cn.hutool</groupId> |
| <artifactId>hutool-all</artifactId> |
| <version>5.8.10</version> |
| </dependency> |
复制
实体Bean
| @Data |
| @AllArgsConstructor |
| @NoArgsConstructor |
| public class User { |
| |
| private String username; |
| |
| private Integer age; |
| |
| private String sex; |
| } |
复制
Map <---> JSON
| |
| HashMap<String, String> map = new HashMap<>(); |
| map.put("username", "张三"); |
| map.put("age", "18"); |
| map.put("sex", "男"); |
| String mapToJSON = JSONObject.toJSONString(map); |
| |
| |
| JSONObject jsonObject = JSONObject.parseObject(mapToJSON); |
| |
| Map<String, Object> newMap = jsonObject; |
复制
JSON <---> Bean
| |
| |
| User jsonToBean = JSONObject.parseObject(JSONObject.toJSONString(map), User.class); |
| |
| String object = "{\"sex\":\"男\",\"age\":\"18\",\"username\":\"张三\"}"; |
| User u = JSONObject.parseObject(object, User.class); |
| |
| |
| User user = new User("李四", 20, "女"); |
| String json = JSONObject.toJSONString(user); |
复制
Bean<---> Map
| |
| User user = new User("李四", 20, "女"); |
| |
| Map<String, Object> beanToMap = new HashMap<>(); |
| |
| beanToMap = BeanUtil.beanToMap(user, beanToMap, CopyOptions.create()); |
| |
| |
| User hutoolToBean = BeanUtil.toBean(map, User.class); |
| |
| User hutoolMapToBean = BeanUtil.mapToBean(map, User.class, true, CopyOptions.create()); |
| |
| User mapToBean = JSONObject.parseObject(JSONObject.toJSONString(map), User.class); |
复制
综上:这里所学得知识使用fastjson是实现Map <--> JSON -> Bean。其余由糊涂工具完成。总结一下parseObject()方法。只要是String就可以进行转换。而toJSONString()是将对象转为String数据类型。
