@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<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 }
以上是如何使用Java中的Jackson函式庫對屬性的順序進行序列化?的詳細內容。更多資訊請關注PHP中文網其他相關文章!