Jackson ObjectMapper - specify serialization order of object properties
The following 2 ObjectMapper configuration are required:
ObjectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
orObjectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)
defines the property serialization order used for POJO fields
Note: does not apply tojava.util.Map
serialization!
and
ObjectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true)
orObjectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)
Feature that determines whether
java.util.Map
entries are first sorted by key before serialization
Spring Boot config example (yaml):
spring:
jackson:
mapper:
SORT_PROPERTIES_ALPHABETICALLY: true
serialization:
ORDER_MAP_ENTRIES_BY_KEYS: true
The annotations are useful, but can be a pain to apply everywhere. You can configure your whole ObjectMapper
to work this way with
Current Jackson versions:
objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
Older Jackson versions:
objectMapper.configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, true);
From the Jackson Annotations documentation:
// ensure that "id" and "name" are output before other properties
@JsonPropertyOrder({ "id", "name" })
// order any properties that don't have explicit setting using alphabetic order
@JsonPropertyOrder(alphabetic=true)