3.Spring Boot 中Jackson配置,ObjectMapper使用详解

本文深入探讨SpringBoot中Jackson的ObjectMapper类如何进行JSON序列化与反序列化,涵盖ObjectMapper的使用方法,如writeValue、readValue及readTree等,并详细解析SpringBoot中Jackson的各项配置参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.前言

1.介绍
  • 上篇文章从spring-boot中引申出了jackson这个杰出的json解析框架,详细的分析了Jackson提供的注解功能,以及它们在controller中的使用,在这篇将介绍Jackson对外提供的API类ObjectMapper,以及Jackson在sping-boot配置文件中的各项配置
2.项目例子
3.进阶文档

二.使用Jackson的ObjectMapper序列化和反序列化Json

  • 注意,Jackson反序列化json为对象的时候,使用的是对象空参构造器,在我们自定义构造器的时候,需要覆写空参构造器
  1. 测试类中所使用的实体

    	public class Apartment {
        private String roommate;
        private String payRentMan;
    
        public Apartment() {
        }
    
        public Apartment(String roommate, String payRentMan) {
            this.roommate = roommate;
            this.payRentMan = payRentMan;
        }
    
        public String getRoommate() {
            return roommate;
        }
    
        public void setRoommate(String roommate) {
            this.roommate = roommate;
        }
    
        public String getPayRentMan() {
            return payRentMan;
        }
    
        public void setPayRentMan(String payRentMan) {
            this.payRentMan = payRentMan;
        }
    }
    
  2. writeValue:对象序列化的时候可以直接将需要序列化的数据,格式化成文件,也可以使用重载方法格式化流输出

     @Test
    public void testWriteValueAsFile() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Apartment apartment = new Apartment("Joey", "Chandler");
        objectMapper.writeValue(new File("target/apartment.json"), apartment);
    }
    

    运行返回,在target文件夹下输出了apartment.json文件

  3. writeValueAsStringwriteValueAsBytes,对象可以直接序列化为字符串和字节

     @Test
    public void testWriteValueAsStringAndByte() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Apartment apartment = new Apartment("Joey", "Chandler");
        String result = objectMapper.writeValueAsString(apartment);
        System.out.println(result);
        byte[] bytes = objectMapper.writeValueAsBytes(apartment);
        System.out.println(new String(bytes));
        assertEquals(result,new String(bytes));
    }
    

    运行返回

    {"roommate":"Joey","payRentMan":"Chandler"}
    {"roommate":"Joey","payRentMan":"Chandler"}
    
  4. readValue,将json串反序列化为对象

     @Test
    public void testReadValueAsBeanFromJson() throws IOException {
        String json = "{ \"roommate\" : \"Joey\", \"payRentMan\" : \"Chandler\" }";
        Apartment apartment = new ObjectMapper().readValue(json, Apartment.class);
        assertEquals(apartment.getPayRentMan(),"Chandler");
    }
    
  5. readValue,将json串反序列化为对象,可以将file文件作为数据源也可以读取网络URL流中数据

     @Test
    public void testReadValueAsBeanFromFileAndURL() throws IOException {
        Apartment apartment = new ObjectMapper().readValue(new File("target/apartment.json"), Apartment.class);
        //Apartment apartment = new ObjectMapper().readValue(new URL("target/apartment.json"), Apartment.class);
        assertEquals(apartment.getPayRentMan(),"Chandler");
    }
    
  6. readTree,将Json解析为Jackson JsonNode对象,从特定的节点中检索数据

     @Test
    public void testReadTree() throws IOException {
        String json = "{ \"roommate\" : \"Joey\", \"payRentMan\" : \"Chandler\" }";
        JsonNode jsonNode = new ObjectMapper().readTree(json);
        assertEquals(jsonNode.get("payRentMan").asText(),"Chandler");
    }
    
  7. 解析json数组到list中,这里需要注意的是,我们需要创建一个带有泛型的模板类对象传入到readValue中用于类型的识别,从而规避泛型的类型擦除

     @Test
    public void testReadValueAsListBean() throws IOException {
        String jsonApartmentArray =
                "[{ \"roommate\" : \"Joey\", \"payRentMan\" : \"Chandler\" }, { \"roommate\" : \"Rachel\", \"payRentMan\" : \"Monica\" }]";
       List<Apartment>  apartments=  new ObjectMapper().readValue(jsonApartmentArray,new TypeReference<List<Apartment>>(){});
        assertEquals(apartments.size(),2);
    }
    
  8. 将数据映射到Map对象中,同list一样,传入map的类型模板

    @Test
    public void testReadValueAsMap() throws IOException {
        String json = "{ \"roommate\" : \"Joey\", \"payRentMan\" : \"Chandler\" }";
        Map<String, Object> map
                =  new ObjectMapper().readValue(json, new TypeReference<Map<String,Object>>(){});
        assertEquals(map.size(),2);
    }
    
  9. 解决反序列化为bean时json多出字段导致UnrecognizedPropertyException异常
    第一种方式使用readTree反序列化为JsonNode
    第二种方式使用configure方式忽略多余字段

    @Test
    public void testMoreProperty() throws IOException {
        String json = "{ \"roommate\" : \"Joey\", \"animal\" : \"dark\"}";
        JsonNode jsonNode = new ObjectMapper().readTree(json);
        assertEquals(jsonNode.get("animal").asText(),"dark");
        ObjectMapper objectMapper= new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        Apartment apartment = objectMapper.readValue(json, Apartment.class);
        assertEquals(apartment.getRoommate(),"Joey");
    }
    
  10. 处理日期有很多种方式,着重介绍2种
    第一种实体类中使用注解@JsonFormat
    第二种将日期格式化规则写入到ObjectMapper中

    @Test
    public void testDateFormat() throws IOException {
        Request request = new Request();
        Apartment apartment = new Apartment("Joey", "Chandler");
        request.setApartment(apartment);
        request.setBillingDate(new Date());
        ObjectMapper objectMapper = new ObjectMapper();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm a z");
        objectMapper.setDateFormat(df);
        String string = objectMapper.writeValueAsString(request);
        System.out.println(string);
    }
    
    class Request
    {
        private Apartment apartment;
        private Date billingDate;
    
        public Apartment getApartment() {
            return apartment;
        }
    
        public void setApartment(Apartment apartment) {
            this.apartment = apartment;
        }
    
        public Date getBillingDate() {
            return billingDate;
        }
    
        public void setBillingDate(Date billingDate) {
            this.billingDate = billingDate;
        }
    }
    
  11. 序列化和反序列化嵌套list,如下

    @Test
    public void testDateFormat2() throws IOException {
        ArrayList<RequestList> requestLists = Lists.newArrayList(new RequestList(Lists.newArrayList(new Apartment("Joey", "Chandler")),1), new RequestList(Lists.newArrayList(new Apartment("Joey", "Chandler")),2));
        ObjectMapper objectMapper = new ObjectMapper();
        String string = objectMapper.writeValueAsString(requestLists);
        System.out.println(string);
        List<RequestList> m =  new ObjectMapper().readValue(string, new TypeReference<List<RequestList>>(){});
        assertEquals(m.size(),2);
    }
    
    class RequestList
    {
        private List<Apartment> apartment;
    
        private Integer id;
    
        public RequestList() {
        }
    
        public RequestList(List<Apartment> apartment, Integer id) {
            this.apartment = apartment;
            this.id = id;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public List<Apartment> getApartment() {
            return apartment;
        }
    
        public void setApartment(List<Apartment> apartment) {
            this.apartment = apartment;
        }
    }
    

三.spring boot中Jackson配置详解

  1. spring.jackson.date-format= 配置日期序列化和反序列化格式, yyyy-MM-dd HH:mm:ss.
  2. spring.jackson.default-property-inclusion= 控制序列化期间包含的属性。配置了Jackson的JsonInclude.Include枚举中的一个值,若配置一般配置non_null表示序列化时忽略属性为null的值,always, non_null, non_absent, non_default, non_empty
  3. spring.jackson.deserialization.*= Jackson反序列化的开关,取值true, false
  4. spring.jackson.generator.*= 开启关闭jackson的生成器,取值true, false
  5. spring.jackson.joda-date-time-format= # 配置日期格式序列化为string的格式,不配置默认使用date-format配置
  6. spring.jackson.locale= 本地化配置
  7. spring.jackson.mapper.*= 开启或者关闭jackson,取值true, false
  8. spring.jackson.parser.*= 开启关闭jsonson的解析器 ,取值true, false
  9. spring.jackson.property-naming-strategy=配置json的key值和实体属性名称之间的转换关系,值一般为PropertyNamingStrategy类中常数或者实现PropertyNamingStrategy子类的全限定名
  10. spring.jackson.serialization.*= Jackson序列化的开关,取值true, false
  11. spring.jackson.time-zone= 格式化日期时使用的时区。例如,“America / Los_Angeles”或“GMT + 10”
  12. spring.jackson.visibility.*= 修改实体类属性域的可见性

四.结尾

  • 上篇文章从spring-boot中引申出了jackson这个杰出的json解析框架,详细的分析了Jackson提供的注解功能,以及它们在controller中的使用
  • 这篇文章,介绍了ObjectMapper是如何序列化和反序列化json,以及Jackson在spring boot中的各项配置

上一篇:Spring Boot 中Json的使用,Jackson注解详解

<think>我们参考了引用内容,特别是引用[1]和引用[3]中关于SpringBoot全局配置Jackson序列化与反序列化的方法。用户希望了解全局配置的方法,因此我们将重点介绍如何通过自定义ObjectMapper和@JsonComponent注解来实现全局配置。###解决方案:SpringBoot全局配置Jackson序列化与反序列化####一、核心配置方法在SpringBoot中,可以通过以下两种主要方式全局配置Jackson:1.**自定义ObjectMapperBean**在配置类中定义`ObjectMapper`Bean,SpringBoot会自动使用它替换默认的ObjectMapper。```javaimportcom.fasterxml.jackson.databind.ObjectMapper;importcom.fasterxml.jackson.databind.SerializationFeature;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;@ConfigurationpublicclassJacksonConfig{@BeanpublicObjectMapperobjectMapper(){ObjectMappermapper=newObjectMapper();//配置序列化行为mapper.enable(SerializationFeature.INDENT_OUTPUT);//美化输出mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);//日期序列化为字符串而非时间戳//配置反序列化行为mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);//忽略未知字段//更多配置...returnmapper;}}```2.**使用`@JsonComponent`自定义序列化/反序列化器**通过`@JsonComponent`注解注册自定义的序列化器或反序列化器,它们会自动被注册到Jackson中[^1]。```javaimportcom.fasterxml.jackson.core.JsonGenerator;importcom.fasterxml.jackson.core.JsonParser;importcom.fasterxml.jackson.core.JsonProcessingException;importcom.fasterxml.jackson.databind.*;importorg.springframework.boot.jackson.JsonComponent;@JsonComponent//自动注册publicclassCustomJsonComponent{//自定义序列化器(示例:将Long类型序列化为字符串)publicstaticclassLongSerializerextendsJsonSerializer<Long>{@Overridepublicvoidserialize(Longvalue,JsonGeneratorgen,SerializerProviderserializers)throwsIOException{gen.writeString(value.toString());//将Long转为字符串输出}}//自定义反序列化器(示例:将字符串反序列化为Long)publicstaticclassLongDeserializerextendsJsonDeserializer<Long>{@OverridepublicLongdeserialize(JsonParserp,DeserializationContextctxt)throwsIOException{returnLong.parseLong(p.getText());}}}```####二、常用配置详解|配置类型|功能|示例代码||----------|------|----------||**序列化配置**|控制Java对象转JSON的行为|`mapper.enable(SerializationFeature.INDENT_OUTPUT)`||**反序列化配置**|控制JSON转Java对象的行为|`mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false)`||**日期格式**|统一设置日期格式|`mapper.setDateFormat(newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"))`||**空值处理**|控制null值的序列化行为|`mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)`|####三、高级场景:注册模块对于复杂数据类型(如Java8日期时间),可通过注册模块实现:```java@BeanpublicObjectMapperobjectMapper(){ObjectMappermapper=newObjectMapper();//注册Java8日期时间模块mapper.registerModule(newJavaTimeModule());//配置日期格式mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);returnmapper;}```####四、配置生效原理SpringBoot通过`JacksonAutoConfiguration`自动配置Jackson。当检测到自定义的`ObjectMapper`Bean时,会优先使用它[^2]。同时,`@JsonComponent`注解的类会被自动扫描并注册到Jackson中[^1]。####五、验证配置是否生效1.**单元测试验证**在测试中注入`ObjectMapper`并检查其行为:```java@AutowiredprivateObjectMapperobjectMapper;@TestvoidtestLongSerialization()throwsJsonProcessingException{Stringjson=objectMapper.writeValueAsString(1000L);Assertions.assertEquals("\"1000\"",json);//验证Long被序列化为字符串}```2.**查看API返回结果**直接调用配置后的接口,观察JSON响应格式。####六、注意事项1.**配置冲突**如果同时存在多个配置源(如`application.yml`和自定义ObjectMapper),SpringBoot的优先级为:**自定义Bean>配置文件**。2.**与其他JSON库共存**如引用[2]所述,若同时存在Jackson和FastJson,需确保Jackson的`HttpMessageConverter`优先级更高(默认如此)。####七、完整配置示例```java@ConfigurationpublicclassJacksonConfig{@BeanpublicObjectMapperobjectMapper(){ObjectMappermapper=newObjectMapper();//基本配置mapper.enable(SerializationFeature.INDENT_OUTPUT);mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);//注册模块mapper.registerModule(newJavaTimeModule());mapper.registerModule(newSimpleModule().addSerializer(Long.class,newLongSerializer()).addDeserializer(Long.class,newLongDeserializer()));returnmapper;}}```>通过以上方法,可全面控制SpringBootJackson的全局序列化与反序列化行为。实际开发中建议根据项目需求选择合适配置方式[^1][^3]。§§相关问题§§1.如何在SpringBoot配置Jackson的日期格式?2.如何忽略Jackson反序列化时的未知字段?3.如何使用Jackson自定义枚举类型的序列化行为?</think>### Spring Boot 全局配置 Jackson 序列化与反序列化方法 在 Spring Boot 中,Jackson 是默认的 JSON 处理器,通过全局配置可以统一管理其序列化(Java对象→JSON)和反序列化(JSON→Java对象)行为。以下是三种核心配置方式: --- #### 一、自定义 ObjectMapper Bean(推荐) 在配置类中定义 `ObjectMapper` Bean,Spring Boot 会自动将其应用于所有 Jackson 操作: ```java import com.fasterxml.jackson.databind.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class JacksonConfig { @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); // 序列化配置 mapper.enable(SerializationFeature.INDENT_OUTPUT); // 美化输出 mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // 日期序列化为字符串而非时间戳 // 反序列化配置 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // 忽略未知字段 mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); // 空字符串转为null // 空值处理 mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 序列化时忽略null字段 // 注册模块(如Java 8时间模块) mapper.registerModule(new JavaTimeModule()); return mapper; } } ``` **生效原理**:Spring Boot 的 `JacksonAutoConfiguration` 会自动检测自定义的 ObjectMapper Bean 并替换默认实现[^3]。 --- #### 二、通过配置文件配置(application.yml) 在 `application.yml` 中直接设置 Jackson 属性: ```yaml spring: jackson: date-format: yyyy-MM-dd HH:mm:ss # 日期格式 time-zone: GMT+8 # 时区 serialization: write-dates-as-timestamps: false # 禁用时间戳 indent-output: true # 美化输出 deserialization: fail-on-unknown-properties: false # 忽略未知字段 default-property-inclusion: non_null # 全局忽略null字段 ``` > **注意**:配置文件优先级低于自定义 ObjectMapper Bean,两者共存时以 Bean 配置为准[^3]。 --- #### 三、使用 `@JsonComponent` 自定义序列化/反序列化器 对特定类型实现精细化控制: ```java import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import org.springframework.boot.jackson.*; @JsonComponent // 自动注册到Jackson public class CustomSerializers { // 自定义序列化器(示例:将Long转为字符串) public static class LongSerializer extends JsonSerializer<Long> { @Override public void serialize(Long value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeString(value.toString()); // 输出为字符串 } } // 自定义反序列化器(示例:空字符串转null) public static class StringDeserializer extends JsonDeserializer<String> { @Override public String deserialize(JsonParser p, DeserializationContext ctx) throws IOException { String value = p.getText(); return value.isEmpty() ? null : value; // 空字符串转null } } } ``` --- ### 四、关键配置项说明 | **配置类型** | **常用选项** | **作用** | |---------------------|-----------------------------------------------------------------------------|---------------------------------------| | **序列化配置** | `SerializationFeature.INDENT_OUTPUT` | 美化JSON输出 | | | `SerializationFeature.WRITE_DATES_AS_TIMESTAMPS` | 日期是否输出为时间戳 | | **反序列化配置** | `DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES` | 遇到未知字段是否报错 | | | `DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT` | 空字符串是否转为null | | **空值处理** | `JsonInclude.Include.NON_NULL` | 序列化时忽略null字段 | | | `JsonInclude.Include.NON_EMPTY` | 忽略空值或空集合 | | **日期处理** | `.registerModule(new JavaTimeModule())` | 支持Java 8日期类型 | | | `.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"))` | 自定义日期格式 | --- ### 五、配置验证方法 1. **单元测试验证** ```java @SpringBootTest class JacksonTest { @Autowired ObjectMapper objectMapper; // 注入配置后的ObjectMapper @Test void testConfig() throws JsonProcessingException { TestObj obj = new TestObj(null, ""); String json = objectMapper.writeValueAsString(obj); // 应输出: {} (忽略null和空字符串) } static class TestObj { private String name; private String address; // 构造方法省略... } } ``` 2. **查看API输出** 直接调用Controller接口,观察返回的JSON格式是否符合预期。 --- ### 六、常见问题解决 1. **配置不生效** - 检查是否有多处配置冲突(如同时存在Bean配置配置文件) - 确保没有手动创建新的 `ObjectMapper` 实例 2. **日期处理异常** ```java // 必须注册JavaTimeModule mapper.registerModule(new JavaTimeModule()); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); ``` 3. **枚举反序列化** ```java // 允许枚举反序列化时忽略大小写 mapper.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE); ``` > 通过合理组合这些配置,可实现全局统一的JSON处理策略,确保系统行为一致性[^1][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值