使用Jackson將Java物件轉為json字串時,可用@JsonPropertyOrder
確保轉出的json字串的順序。
例如下面是簡單的POJO Customer
類別。
Customer
public class Customer {
private String email;
private Integer age;
private String name;
private Long id;
// getters and setters
}
使用Jackson的ObjectMapper
將物件轉為json字串。
Customer customer = new Customer();
customer.setEmail("john@abc.com");
customer.setAge(30);
customer.setName("John");
customer.setId(1L);
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writerWithDefaultPrettyPrinter().
writeValueAsString(customer);
System.out.println(jsonString);
未使用@JsonPropertyOrder
則印出的json字串可能如下
{
"email" : "john@abc.com",
"age" : 30,
"name" : "John",
"id" : 1
}
下面在Customer
類別前掛上@JsonPropertyOrder
並依想要輸出的json字串順序來排列成員名稱。
Customer
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonPropertyOrder({"id", "name", "email", "age"})
public class Customer {
private String email;
private Integer age;
private String name;
private Long id;
// getters and setters
}
轉為json字串時就會依設定的名稱順序輸出。
{
"id" : 1,
"name" : "John",
"email" : "john@abc.com",
"age" : 30
}
沒有留言:
張貼留言