Configuring ObjectMapper in Spring

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

    
        
            
                
                    
                        
                            
                                
                            
                        
                    
                
            
        
    
    

    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 {
    
        @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 handledType() {
            return CustomObject.class;
        }
    }
    

    No XML configuration ((...)) is needed in my solution.

提交回复
热议问题