Home > Software design >  How can I overwrite a application.yml in a class attribute?
How can I overwrite a application.yml in a class attribute?

Time:11-20

I have this property in my properties yml file:

jackson:
    default-property-inclusion: non_null
    serialization:
        write-empty-json-arrays: false
    serialization-inclusion: NON_EMPTY

What it does is prohibit JSON empty arrays. But for a specific attribute in a class, I want to be able to return it empty. Is there a way or property I can use to make this? Thanks!

CodePudding user response:

The only way would be to create another ObjectMapper and then use that one to serialize that specific class.

@Configuration
class JacksonConfiguration {

    @Bean
    fun mainObjectMapper() = jacksonObjectMapper().apply {
        setSerializationInclusion(JsonInclude.Include.NON_NULL)
        setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
    }

    @Bean
    fun otherObjectMapper() = jacksonObjectMapper().apply {
        setSerializationInclusion(JsonInclude.Include.NON_NULL)
    }
}

However, this seems a little bit overkill for such a simple thing.


Another option, which is maybe the best for you is to use the @JsonInclude annotation. You would use it as follows:

@JsonInclude(JsonInclude.Include.ALWAYS)
List<String> propertyToSerializeEvenIfEmptyOrNull;
  • Related