
@JsonPropertyOrder 是在类级别使用的注释。它采用字段列表作为属性,该列表定义字段在对象 JSON 序列化生成的字符串中出现的顺序。可以首先序列化注释声明中包含的属性(按定义的顺序),然后序列化定义中未包含的任何属性。
语法
public @interface JsonPropertyOrder
示例
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.*;
import java.io.*;
public class JsonPropertyOrderTest {
public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException {
Employee emp = new Employee();
emp.setFirstName("Adithya");
emp.setEmpId(25);
emp.setLastName("Jai");
emp.getTechnologies().add("Java");
emp.getTechnologies().add("Scala");
emp.getTechnologies().add("Python");
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter().writeValue(System.out, emp);
}
}
// Employee class
@JsonPropertyOrder({
"firstName",
"lastName",
"technologies",
"empId"
})
class Employee {
private int empId;
private String firstName;
private String lastName;
private List technologies = new ArrayList<>();
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List getTechnologies() {
return technologies;
}
public void setTechnologies(List technologies) {
this.technologies = technologies;
}
} 输出
{
"firstName" : "Adithya",
"lastName" : "Jai",
"technologies" : [ "Java", "Scala", "Python" ],
"empId" : 125
}











