[Spring]~@JsonProperty(字段映射名稱)

作用

@JsonProperty 可以指定某個屬性和json映射的名稱。例如我們有個json字符串爲{“user_name”:”aaa”},而java中命名要遵循駝峯規則,則爲userName,這時通過@JsonProperty 註解來指定兩者的映射規則即可。

實體類

@JsonIgnoreType
public class JsonTestModel {
    String name;
    @JsonProperty("ti_me")
    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);
        json = "{\"name\":\"@JsonIgnoreProperties測試\",\"ti_me\":1575431118191}";
        //反序列化
        JsonTestModel readValue = mapper.readValue(json, JsonTestModel.class);
        System.out.println("name:"+readValue.getName());
        System.out.println("time:"+readValue.getTime());

    }

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

}

測試結果

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