Jackson允许用户使用@JsonProperty(index = ?)注解为ObjectNode属性指定显式的序列化顺序。这意味着,给定属性a, b, c,我可以指示Jackson按以下顺序序列化它们:b, a, c。我控制精确的序列化顺序。不使用注解是否可以实现相同的功能?我不想按字母排序。我想指定一个明确的排序顺序。
@JsonProperty(index = ?)
ObjectNode
a, b, c
b, a, c
k4emjkb11#
您可以扩展com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector类,并通过重写findSerializationPropertyOrder方法为任何您想要的类提供订单。
com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector
findSerializationPropertyOrder
import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.introspect.AnnotatedClass; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.json.JsonMapper; import lombok.Data; public class JacksonAnnotationIntrospectorApp { private final static JsonMapper JSON_MAPPER = JsonMapper.builder() .enable(SerializationFeature.INDENT_OUTPUT) .annotationIntrospector(new DynamicOrderJacksonAnnotationIntrospector()) .build(); public static void main(String[] args) throws Exception { var pojo = new DynamicOrderPojo(); pojo.setA("A"); pojo.setB(1); pojo.setC(3.33); JSON_MAPPER.writeValue(System.out, pojo); } } class DynamicOrderJacksonAnnotationIntrospector extends JacksonAnnotationIntrospector { @Override public String[] findSerializationPropertyOrder(AnnotatedClass ac) { if (ac.getRawType() == DynamicOrderPojo.class) { return new String[]{"b", "a", "c"}; } return super.findSerializationPropertyOrder(ac); } } @Data class DynamicOrderPojo { private String a; private Integer b; private Double c; }
以上代码打印:
{ "b" : 1, "a" : "A", "c" : 3.33 }
参见:
1条答案
按热度按时间k4emjkb11#
您可以扩展
com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector
类,并通过重写findSerializationPropertyOrder
方法为任何您想要的类提供订单。以上代码打印:
参见: