点击 Mr.绵羊的知识星球 解锁更多优质文章。
一、介绍
1. 简介
Jackson是一个简单的、功能强大的、基于Java的应用库。它可以很方便完成Java对象和Json对象(xml文档or其它格式)进行互转。也是Spring家族的默认JSON/XML解析器。
2. Jackson的三个核心模块
(1) jackson-core:定义了低级的流式API,包括了JSON处理细节。 (2) jackson-annotations:包含了Jackson的注解。 (3) jackson-databind:实现了对象和JSON之间的转换,这个包依赖上面两个包。
不怎么了解JSON的同学:JSON介绍
二、实际应用
1. 案例一
在我们编写的接口中,经常会有一些冗余字段没有赋值,如果有非常多的冗余字段都为null,不仅给调试接口带来的不必要的麻烦,也占用了资源。
(1) 场景:
接口调用方要求我们提供的createAccount接口,如果接口调用异常响应:错误编码和信息。成功响应新增的账号信息。
(2) 代码:git地址
a. pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.7.5</version></dependency>
b. Controller代码
import com.wxy.common.exception.BusinessException;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;import java.time.LocalDateTime;/** * JacksonAccountController * * @author wxy * @since 2023-01-23 */@RestControllerpublic class JacksonAccountController { /** * 创建账号 * * @param accountVo accountVo * @return JacksonRsp<AccountVo> */ @PostMapping("/accounts") public JacksonRsp<AccountVO> create(@RequestBody AccountVO accountVo) { JacksonRsp<AccountVO> jacksonRsp = new JacksonRsp<>(); try { jacksonRsp.setResult(createAccount(accountVo, true)); } catch (Exception e) { jacksonRsp.setCode("CreateAccountError"); jacksonRsp.setMessage(e.getMessage()); } return jacksonRsp; } /** * 创建账号 * * @param accountVo 账号实体 * @param flag 是否正常执行 * @return AccountVo */ private AccountVO createAccount(AccountVO accountVo, boolean flag) { if (flag) { // 创建账号成功 accountVo.setCreateTime(LocalDateTime.now()); return accountVo; } else { // 创建失败 抛出异常 throw new BusinessException("create account error"); } }}
c. VO代码
import java.time.LocalDateTime;/** * AccountVo * * @author wxy * @since 2023-01-23 */public class AccountVO { private String id; private String name; private String desc; private LocalDateTime createTime; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; }}
d. JacksonRsp代码
/** * JacksonRsp * * @param <T> 结果类型 * @author wxy * @since 2023-01-23 */public class JacksonRsp<T> { /** * 编码 */ private String code; /** * 错误信息 */ private String message; /** * 响应结果 */ private T result; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getResult() { return result; } public void setResult(T result) { this.result = result; }}
正常响应结果(响应有null值):
{
"code": null,
"message": null,
"result": {
"id": "account_01",
"name": "账号01",
"desc": "this is account",
"createTime": "2023-01-23T16:12:24.6055759"
}
}
异常响应结果:
{
"code": "CreateAccountError",
"message": "create account error",
"result": null
}
d. JacksonConfig
import com.fasterxml.jackson.annotation.JsonInclude;import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.databind.JsonSerializer;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializerProvider;import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;import java.io.IOException;/** * JacksonConfig * * @author wxy * @since 2022-01-23 */@Configurationpublic class JacksonConfig { @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); // 屏蔽掉值为null的参数 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); /// 修改值为null的参数值(需要处理打开方法并修改逻辑) /*objectMapper.getSerializerProvider() .setNullValueSerializer(new JsonSerializer<>() { @Override public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(""); } });*/ return objectMapper; }}
正常响应结果(增加JacksonConfig,响应无null值):
{
"result": {
"id": "account_01",
"name": "账号01",
"desc": "this is account",
"createTime": "2023-01-23T17:52:55.7194902"
}
}
异常响应结果:
{
"code": "CreateAccountError",
"message": "create account error"
}
三、总结
Jackson的使用方式还有很多,感兴趣可以网上搜索。去除响应JSON中为null的参数也有很多做法,例如:面向对象根据不同场景返回不同响应体(关注案例三)
参考文章:
1. Jackson介绍