[Spring]~@JsonPropertyOrder(序列化時字段排序)

作用

序列化時生效,將返回的json按字段排序。

實體類

@JsonPropertyOrder(value = {"time","name"})
public class JsonTestModel {
    String name;
    Date time;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getTime() {
        return time;
    }
    public void setTime(Date time) {
        this.time = time;
    }
}

測試類

public class JsonTests {

    static JsonTestModel testModel;

    @BeforeClass
    public static void setTestModel(){
        JsonTestModel jsonTestModel = new JsonTestModel();
        jsonTestModel.setName("@JsonIgnoreProperties測試");
        jsonTestModel.setTime(new Date());
        testModel = jsonTestModel;
    }

    @Test
    public void test() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        //序列化
        String json = mapper.writeValueAsString(testModel);
        System.out.println(json);
    }

    @AfterClass
    public static void tearDown() {
        testModel = null;
    }

}

測試結果

不加註解

{"name":"@JsonIgnoreProperties測試","time":1575445808075}

加註解

{"time":1575445919216,"name":"@JsonIgnoreProperties測試"}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章