jackson序列化key排序

发布时间 2023-11-02 18:34:00作者: 白日梦丶

对象在序列化的时候对key进行排序

使用 

JsonPropertyOrder
``` java
@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE,
ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonPropertyOrder
{
/**
* Order in which properties of annotated object are to be serialized in.
* 指定key的排序
*/
public String[] value() default { };

/**
* Property that defines what to do regarding ordering of properties
* not explicitly included in annotation instance. If set to true,
* they will be alphabetically ordered; if false, order is
* undefined (default setting)
   * 为true的时候,则按字母排序。
*/
public boolean alphabetic() default false;
}
```
测试
``` java
public class TestJackson {

public static void main(String[] args) throws IOException {
TestA a = new TestA();
a.setA("");
a.setB("");
a.setC("");
a.setD("");
a.setE("");
a.setF("");
a.setG("");
a.setH("");
a.setI("");
a.setJ("");
a.setK("");
a.setL("");
a.setZ("");
System.out.println(JsonUtil.encode(a));
}
@Data
@JsonPropertyOrder(alphabetic = true)
public static class TestA{
private String z= "";
private String b = "2";
private String d= "";
private String t= "";
private String c= "";
private String g= "";
private String k= "";
private String f= "";
private String e= "";
private String a = "1";
private String h= "";
private String i= "";
private String j= "";
private String l= "";
private String a1= "";
private String a2= "";
private String a3= "";
}
}
```
结果:
``` json
{"a":"","a1":"","a2":"","a3":"","b":"","c":"","d":"","e":"","f":"","g":"","h":"","i":"","j":"","k":"","l":"","t":"","z":""}
```