如何保留POJO中定义的JSON响应顺序

时间:2019-06-03 20:48:20

标签: java json jackson

我有一个POJO类A,我希望字段按我定义的顺序排列,但是“ 1800number”出现在响应的最后,因为它以数字开头。我该如何避免?

 @JsonInclude(JsonInclude.Include.NON_NULL)
 public class A {
    private String name;
    private String age;
    private String dept;
    @JsonProperty("1800number")
    private String _1800number;
    private String email;
 } 

这就是我得到回复的方式

{
  "name": "Mark",
  "age": "52",
  "dept": "Civil",
  "email": "mark@gmail",
  "1800number": "12345"
}

我在gradle中使用以下库

 compile('com.fasterxml.jackson.core:jackson-annotations:2.8.3')
 compile('com.fasterxml.jackson.core:jackson-databind:2.8.3')

1 个答案:

答案 0 :(得分:2)

使用@JsonPropertyOrder注释:

@JsonPropertyOrder({ "name", "age", "dept", "1800number", "email" })
public class A {
    private String name;
    private String age;
    private String dept;
    @JsonProperty("1800number")
    private String _1800number;
    private String email;
 }