Configuring ObjectMapper in Spring

前端 未结 12 1879
迷失自我
迷失自我 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 11:18

    I am using Spring 3.2.4 and Jackson FasterXML 2.1.1.

    I have created a custom JacksonObjectMapper that works with explicit annotations for each attribute of the Objects mapped:

    package com.test;
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    
    public class MyJaxbJacksonObjectMapper extends ObjectMapper {
    
    public MyJaxbJacksonObjectMapper() {
    
        this.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
                .setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.ANY)
                .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE)
                .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
                .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);
    
        this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        }
    }
    

    Then this is instantiated in the context-configuration (servlet-context.xml):

    
        
    
            
                
                    
                
            
    
        
    
    

    This works fine!

提交回复
热议问题