jackson是一個常用的json庫,在java開發中被廣泛使用。當我們的對象中有null值時,jackson會怎么處理呢?
public class User { private String name; private Integer age; private Boolean married; // 省略getter和setter方法 }
如果我們的User對象中有屬性為null,例如:
User user = new User(); user.setName("Tom"); user.setAge(null); user.setMarried(true);
那么jackson在序列化時會把null值轉化為json的null值,即
{ "name": "Tom", "age": null, "married": true }
而在反序列化時,當json中有null值時,jackson會自動把對應的屬性賦值為null:
String jsonStr = "{\"name\": \"Jerry\", \"age\": null, \"married\": false}"; User user = objectMapper.readValue(jsonStr, User.class); System.out.println(user); // User{name='Jerry', age=null, married=false}