Jackson custom serializer by field name?

前端 未结 2 1902
傲寒
傲寒 2021-01-20 21:03

I have a POJO to be serialized which has field of type Object named representation and I have a custom serializer written for it.

相关标签:
2条回答
  • 2021-01-20 21:24

    Just to add to the excellent answer by cassiomolin if you're trying to use this with Spring Boot and Kotlin to use your custom Jackson ObjectMapper:

    // the custom serializer
    class CustomSerializer : JsonSerializer<Any>() {
      override fun serialize(value: Any?, 
                             gen: JsonGenerator?, 
                             serializers: SerializerProvider?) {
        gen?.let { 
          gen.writeObject(content) 
         
          // ...
        }
      }
    }
    
    // the mixin
    interface EventMixIn {
      @JsonProperty("representation")
      @JsonSerialize(using = CustomSerializer::class)
      fun getRepresentation(): Any?
    }
    
    // the config with the bean
    @Configuration
    class AppConfig {
      @Bean
      fun createObjectMapper(): MappingJackson2HttpMessageConverter {
        val objectMapper = ObjectMapper()
        objectMapper.addMixIn(Event::class.java, EventMixIn::class.java)
        return MappingJackson2HttpMessageConverter(objectMapper)
      }
    }
    
    0 讨论(0)
  • 2021-01-20 21:43

    Have you ever considered Jackson mix-in annotations?

    Jackson mix-in annotations

    It's a great alternative when modifying the classes is not an option. You can think of it as kind of aspect-oriented way of adding more annotations during runtime, to augment statically defined ones.

    Define a mix-in annotation interface (class would do as well):

    public interface EventMixIn {
    
        @JsonProperty("representation")
        @JsonSerialize(using = CustomSerializer.class)
        Object getRepresentation();
    }
    

    Then configure ObjectMapper to use the defined interface as a mix-in for your POJO:

    ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
                                            .addMixIn(User.Event.class, EventMixIn.class); 
    

    Usage considerations

    Here are some usage considerations:

    • All annotation sets that Jackson recognizes can be mixed in.
    • All kinds of annotations (member method, static method, field, constructor annotations) can be mixed in.
    • Only method (and field) name and signature are used for matching annotations: access definitions (private, protected, ...) and method implementations are ignored.

    For more details, you can have a look at this page.

    0 讨论(0)
提交回复
热议问题