Jackson ObjectMapper - specify serialization order of object properties

后端 未结 9 1656
梦毁少年i
梦毁少年i 2020-11-27 17:38

I\'m implementing a RESTful web service where user has to send a signed verification token along with the request so that I could ensure that the request has not been tamper

9条回答
  •  清酒与你
    2020-11-27 18:22

    You can use mix-in and specify the order of properties as you like:

    import com.fasterxml.jackson.annotation.JsonPropertyOrder;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.stereotype.Component;
    
    @Component
    public final class ObjectMapperUtils {
    
        private static final ObjectMapper MAPPER = new ObjectMapper();
    
        static {
            MAPPER.addMixIn(Object.class, IdFirst.class);
        }
    
        @Bean
        public ObjectMapper objectMapper() {
            return MAPPER;
        }
    
        @JsonPropertyOrder({"id", "...", "..."})
        private abstract static class IdFirst {}
    
    }
    

提交回复
热议问题