1、ObjectMapper与JSONObject比较
1、ObjectMapper属于jackson库的一部分,JSONObject属于alibaba的fastjson,两者各有优劣,可根据自己的系统环境选择使用哪种技术。
2、目前来看,Jackson社区相对活跃,Spring MVC和Spring Boot都默认使用Jackson。
jackson–core(核心包)、jackson–databind(数据绑定包)、jackson–annotations(注解包)
//JSONObject依赖包
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.42</version>
</dependency>
//ObjectMapper依赖包
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.14.2</version>
</dependency>
2、ObjectMapper使用概述
ObjectMapper通过writeValue()实现序列化,通过readValue()实现反序列化。
ObjectMapper通过Feature枚举类,初始化了很多的默认配置。
2.1、工程的pom.xml导包信息
spring–boot–starter–web包中包含了jackson包,不需要单独导入
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.17</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.txc</groupId>
<artifactId>objectmapper</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>objectmapper</name>
<description>objectmapper</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.2、创建案例中的测试对象
案例中使用lombok注解生成get和set方法,也可以直接写get和set方法
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {
private String stu_id;
private String stu_name;
}
2.3、对象和JSON相互转化
2.3.1、测试代码
/**
* 实现对象和JSON之间互转
*/
@RequestMapping("/jsonObjectChange")
@ResponseBody
public void jsonObjectChange() throws Exception{
ObjectMapper mapper = new ObjectMapper();
String param = "{"stu_id":"1001","stu_name":"晓春","stu_sex":"男","stu_age":"34","stu_addr":"安徽合肥","stu_pwd":"123456"}";
//将字符串转换为对象—反序列化过程
Student student = mapper.readValue(param, Student.class);
System.out.println("===json转对象==="+student.toString());
//将对象转化成JSON—序列化过程
String json = mapper.writeValueAsString(student);
System.out.println("===对象转json==="+json);
}
2.3.2、测试结果展示
2.4、集合和JSON像话转化
2.4.1、测试代码
/**
* 集合和JSON相互转化
*/
@RequestMapping("/listAndJSONChange")
@ResponseBody
public void arrayToObject() throws Exception{
Student student1=new Student("1001","晓春1","男","34","安徽合肥","123456");
Student student2=new Student("1002","晓春2","男","34","安徽合肥","123456");
ObjectMapper mapper = new ObjectMapper();
//集合转json
String param = mapper.writeValueAsString(Arrays.asList(student1,student2));
System.out.println("==集合转json=="+param);
//数组json转化成集合
List<Student> list= mapper.readValue(param, List.class);
System.out.println("==数组json转集合=="+list);
}
2.4.2、测试结果展示
2.5、Map和JSON相互转化
2.5.1、测试代码
/**
* map和json相互转化
*/
@RequestMapping("/mapAndJsonChange")
@ResponseBody
public void mapAndJsonChange() throws Exception{
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = new HashMap<>();
map.put("id", "1001");
map.put("name","晓春");
map.put("student", new Student("6","6","6","6","6","6"));
String param = mapper.writeValueAsString(map);
System.out.println("===map转json==="+param);
Map<String, Object> resultMap = mapper.readValue(param, Map.class);
System.out.println("===json转map==="+resultMap);
}
2.5.2、测试结果展示
3、如果不需要JSON与其他转化,而是直接获取
使用readTree,通过节点树的方式直接获取JSON属性对应的值
使用链接:https://blog.csdn.net/tangshiyilang/article/details/134326627
4、在Springboot工程中,通过配置的方式,配置ObjectMapper配置
方便使用,一次性配置,会在springboot工程启动的时候自动获取配置
@Configuration
public class ObjectMapperConfig {
@Bean("objectMapper")
public ObjectMapper getObjectMapper(){
ObjectMapper mapper = new ObjectMapper();
//属性为NULL 不序列化
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//属性为默认值不序列化
mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
//反序列化时,遇到未知属性不报错
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//如果是空对象的时候,不抛异常
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//修改序列化后日期格式
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
return mapper;
}
}
5、常见的ObjectMapper配置及问题总结
5.1、如果生成的JSON使用的是单引号,解析会失败
问题的json样式:String param=“{‘stu_id‘:’1001′,’stu_name’:’晓春’}”;
解决博客地址:https://blog.csdn.net/tangshiyilang/article/details/134275584
5.2、生成的JSON字符串属性没有双引号或者单引号问题
问题json样式:String param=“{stu_id:”1001″,stu_name:”晓春”}”;
解决博客地址:https://blog.csdn.net/tangshiyilang/article/details/134281368
5.3、JSON字符串转化对象,JSON中的属性名称与对象属性名称不同问题
问题描述:JSON字符串中出现了属性名称与对象中的名称不一致的情况,而造成的解析错误。
解决博客地址:https://blog.csdn.net/tangshiyilang/article/details/134281585
5.4、对象转化成JSON字符串,如果属性值为null,不被序列化
解决博客地址:解析JSON字符串:属性值为null的时候不被序列化-CSDN博客
6、源码下载
https://download.csdn.net/download/tangshiyilang/88512083
原文地址:https://blog.csdn.net/tangshiyilang/article/details/134275828
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_42872.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!