Configuring ObjectMapper in Spring

前端 未结 12 1701
迷失自我
迷失自我 2020-11-22 10:46

my goal is to configure the objectMapper in the way that it only serialises element which are annotated with @JsonProperty.

In order to do

相关标签:
12条回答
  • 2020-11-22 10:59

    There is org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean for a long time. Starting from 1.2 release of Spring Boot there is org.springframework.http.converter.json.Jackson2ObjectMapperBuilder for Java Config.

    In String Boot configuration can be as simple as:

    spring.jackson.deserialization.<feature_name>=true|false
    spring.jackson.generator.<feature_name>=true|false
    spring.jackson.mapper.<feature_name>=true|false
    spring.jackson.parser.<feature_name>=true|false
    spring.jackson.serialization.<feature_name>=true|false
    spring.jackson.default-property-inclusion=always|non_null|non_absent|non_default|non_empty
    

    in classpath:application.properties or some Java code in @Configuration class:

    @Bean
    public Jackson2ObjectMapperBuilder jacksonBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        return builder;
    }
    

    See:

    • Official docs 74.3 Customize the Jackson ObjectMapper
    • https://dzone.com/articles/latest-jackson-integration
    • How do you globally set Jackson to ignore unknown properties within Spring?
    • http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBean.html
    0 讨论(0)
  • 2020-11-22 11:00

    To configure a message converter in plain spring-web, in this case to enable the Java 8 JSR-310 JavaTimeModule, you first need to implement WebMvcConfigurer in your @Configuration class and then override the configureMessageConverters method:

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modules(new JavaTimeModule(), new Jdk8Module()).build()
                .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
    }
    

    Like this you can register any custom defined ObjectMapper in a Java-based Spring configuration.

    0 讨论(0)
  • 2020-11-22 11:03

    In Spring Boot 2.2.x you need to configure it like this:

    @Bean
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        return builder.build()
    }
    

    Kotlin:

    @Bean
    fun objectMapper(builder: Jackson2ObjectMapperBuilder) = builder.build()
    
    0 讨论(0)
  • 2020-11-22 11:09

    It may be because I'm using Spring 3.1 (instead of Spring 3.0.5 as your question specified), but Steve Eastwood's answer didn't work for me. This solution works for Spring 3.1:

    In your spring xml context:

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper" ref="jacksonObjectMapper" />
            </bean>        
        </mvc:message-converters>
    </mvc:annotation-driven>
    
    <bean id="jacksonObjectMapper" class="de.Company.backend.web.CompanyObjectMapper" />
    
    0 讨论(0)
  • 2020-11-22 11:10

    If you want to add custom ObjectMapper for registering custom serializers, try my answer.

    In my case (Spring 3.2.4 and Jackson 2.3.1), XML configuration for custom serializer:

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="false">
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="serializers">
                            <array>
                                <bean class="com.example.business.serializer.json.CustomObjectSerializer"/>
                            </array>
                        </property>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    

    was in unexplained way overwritten back to default by something.

    This worked for me:

    CustomObject.java

    @JsonSerialize(using = CustomObjectSerializer.class)
    public class CustomObject {
    
        private Long value;
    
        public Long getValue() {
            return value;
        }
    
        public void setValue(Long value) {
            this.value = value;
        }
    }
    

    CustomObjectSerializer.java

    public class CustomObjectSerializer extends JsonSerializer<CustomObject> {
    
        @Override
        public void serialize(CustomObject value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,JsonProcessingException {
            jgen.writeStartObject();
            jgen.writeNumberField("y", value.getValue());
            jgen.writeEndObject();
        }
    
        @Override
        public Class<CustomObject> handledType() {
            return CustomObject.class;
        }
    }
    

    No XML configuration (<mvc:message-converters>(...)</mvc:message-converters>) is needed in my solution.

    0 讨论(0)
  • 2020-11-22 11:11

    I found the solution now based on https://github.com/FasterXML/jackson-module-hibernate

    I extended the object mapper and added the attributes in the inherited constructor.

    Then the new object mapper is registered as a bean.

    <!-- https://github.com/FasterXML/jackson-module-hibernate -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <array>
                <bean id="jsonConverter"
                class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                    <property name="objectMapper">
                        <bean class="de.company.backend.spring.PtxObjectMapper"/>
                    </property>
                </bean>
            </array>
        </property>
    </bean>   
    
    0 讨论(0)
提交回复
热议问题