@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); } } //员工阶层 @JsonPropertyOrder({ "firstName", "lastName", "technologies", "empId" }) class Employee { private int empId; private String firstName; private String lastName; private List<String> 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<String> getTechnologies() { return technologies; } public void setTechnologies(List<String> technologies) { this.technologies = technologies; } }
输出结果
{ "firstName" : "Adithya", "lastName" : "Jai", "technologies" : [ "Java", "Scala", "Python" ], "empId" : 125 }