![](/img/trans.png)
[英]How to ignore certain fields with Jackson's ObjectMapper.readerForUpdating
[英]How to force Jackson object mapper to ignore not full fields with readerForUpdating().readValue method
我有一個類(Jackson 注釋/getter/setter/etc 被省略):
public class Sample {
public String name;
public Integer value;
}
我有一個實例,例如:
Sample sample = new Sample("one", null)
,
我有一個 json 字符串:
{"name" = "two", "value" = 3}
我用 json 更新對象:
ObjectMapper mapper = new ObjectMapper();
mapper.readerForUpdating(sample).readValue(json);
更新后我的對象看起來像這樣:
[Sample: name = "two", value = 3]
但是我不需要像name
一樣覆蓋非空字段,所以更新后我的對象看起來像這樣:
[Sample: name = "one", value = 3]
不幸的是,我無法編輯我的類和 Jackson 注釋,所以我需要以某種方式更改我的映射器的配置。 有沒有辦法做到這一點?
readerForUpdating
方法背后的想法不是創建對象的新實例,只是將傳遞的對象的值替換到對象中進行更新。
我有同樣的問題,只想替換不為空的值,但要做到這一點,我需要隔離 ObjectMapper 並將其配置為不傳輸空值,結合readerForUpdating
方法做我們想要的:
public static void updateModels(Object original,Object data) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
try {
objectMapper.readerForUpdating(original).readValue(objectMapper.writeValueAsBytes(data));
} catch (IOException e) {
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.