一、忽略null值
在實際開發中,我們經常會遇到需要忽略null值的情況,例如返回給前端的數據如果有null值會讓前端出現異常。這時我們可以使用ObjectMapper類中的一些方法來忽略null值。
首先,我們可以在全局配置中設置ObjectMapper的序列化參數:
ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
在這個配置中,我們將ObjectMapper的序列化策略設置為NON_NULL,這樣在序列化Java對象時,只有非null值才會被序列化。
另外,如果我們只需要在某個特定的情況下忽略null值,我們可以使用@JsonIgnoreProperties註解:
public class User {
private Long id;
private String name;
@JsonIgnoreProperties(value = {"email"})
private String email;
// getters and setters
}
在這個註解中,我們將email屬性標註為需要忽略的屬性。這樣,在序列化User對象時,email屬性的值為null就會被忽略。
二、自定義配置
除了忽略null值外,我們還可以自定義ObjectMapper的配置,以滿足我們的具體需求。
比如,我們可以設置日期格式:
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
這樣,在序列化或反序列化Java對象中的日期屬性時,都會按照指定的格式進行處理。
另外,我們還可以自定義序列化或反序列化的實現:
public class CustomSerializer extends JsonSerializer {
@Override
public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}
}
public class CustomDeserializer extends JsonDeserializer {
@Override
public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return LocalDate.parse(p.getText(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
}
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(LocalDate.class, new CustomSerializer());
module.addDeserializer(LocalDate.class, new CustomDeserializer());
mapper.registerModule(module);
在這個例子中,我們自定義日期類型LocalDate的序列化和反序列化實現,並將它們註冊到ObjectMapper中。這樣,在序列化或反序列化Java對象中的LocalDate屬性時,都會使用我們自定義的實現。
三、參考資源
通過本文的介紹,相信讀者對ObjectMapper已經有了整體的了解。如果還需要更深入地學習ObjectMapper,可以參考以下資源:
1. ObjectMapper官方文檔:https://github.com/FasterXML/jackson-databind/
2. 《深入淺出Spring Boot 2.x》一書的第十章
3. ObjectMapper的Github倉庫:https://github.com/FasterXML/jackson-databind/
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/253521.html
微信掃一掃
支付寶掃一掃