如何使用Jackson的ObjectMapper.readerForUpdating忽略特定字段

5

我正在使用Jackson 2.7.0

当我尝试更新一个已存在的对象并添加一些新值时,我想忽略encodingType

ObjectMapper om = new ObjectMapper();
om.readerForUpdating(message).readValue(messageSubset);

message 包含一个 encodingType 的值。
messageSubset(JSON字符串)不包含 encodingType 的条目(没有键值对)。

我尝试过以下方法:

  • 对于 ObjectMapper:
    • om.setSerializationInclusion(Include.NON_EMPTY);
  • 在 message 类上:
    • @JsonIgnoreProperties(ignoreUnknown = true)
    • @JsonIgnoreProperties(value = { "encodingType" })
    • @JsonInclude(Include.NON_EMPTY)
    • @JsonInclude(Include.NON_NULL)
  • 在字段和 getter/setter 上:
    • @JsonInclude(Include.NON_EMPTY)
    • @JsonInclude(Include.NON_NULL)
    • @JsonIgnore
    • @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

以上方法都无效!有什么帮助吗?
我想这可能与 readerForUpdating 有关,或者是其中一个正在被更新的事实。


我刚刚尝试了你的代码,使用一个虚拟的Message类,其中encodingType是一个String,它运行得很好。不需要任何注释。你能否发布一下message类的代码和一个示例JSON? - Manos Nikolaidis
我通过以下方式配置ObjectMapper解决了问题:om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);om.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);并在Message类的正确属性上进行如下设置:setter 上使用@JsonIgnoregetter 上使用@JsonProperty - Thomas Stubbe
1个回答

3
我通过这样配置ObjectMapper解决了问题(不确定是否需要所有这些):
om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); om.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
对于需要的属性,针对Message类:
在setter上使用@JsonIgnore(在解析为Java对象时排除它) 在getter上使用@JsonProperty (在解析为JSON对象时包含它)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接