天天看點

Jackson 指定序列化順序

方法1: 類加上注解@JsonPropertyOrder,裡面按需要指定的順序寫上字段

@JsonPropertyOrder({"firstname", "lastname", "birthday"})      

方法2:成員變量加上注解@JsonProperty,通過value指定順序(數字越小越靠前)

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Nc {

    /**
     * 播報方式
     */
    @JsonProperty(index = 2)
    private String channel;

    /**
     * 播報内容
     */
    @JsonProperty(index = 1)
    private String ct;

    /**
     * 消息編碼
     */
    @JsonProperty(index = 3)
    private String charset;

}      

輸出結果(因為charset沒有值,為null,而且設定了 @JsonInclude(JsonInclude.Include.NON_NULL), 是以沒有顯示該字段):

{
    "nc": {
        "ct": "12345",
        "channel": "1"
    }
}      

繼續閱讀