Jackson ObjectMapper 解析 HashMap returns 所有字段 = NULL

Jackson ObjectMapper parsing of HashMap returns all fields = NULL

我正在尝试使用

将 HashMap 数据解析为 POJO
Object parsedMessage = objectMapper.convertValue(receivedMessage, destinationClass);

其中 receivedMessage 是一个 HashMap(之前从 JSON 解析)并包含各种类型的字段 - Integer、Boolean、String、LinkedHashMap。

我定义了 destinationClass 以便它包含 some 在 HashMap 键中找到的字段,与键的名称完全相同(区分大小写)。

指令执行无异常,但parsedMessage中所有字段为null。可能是什么原因?类似的指令在代码的其他地方工作得很好。

我已经解决了

事实证明,无论 destinationClass 中的 Java 字段如何命名,Jackson(至少,默认情况下)假定它以 lowerCamelCase 命名。 因此,如果您的 hashmap 具有 "YourField" 而您的 POJO 具有相同的 "YourField",那么它将无法工作 如果您不从一开始就在两端使用 lowerCamelCase! (如果你解析序列化的 .NET JSON,你最终会得到 UpperCamelCase)。

因为 Jackson 假设你的 POJO 的 "YourField" 被命名为 "yourField" 用于匹配!

要解决此问题,可以:

您的 HashMap 键必须是 lowerCamelCase。

创建不区分大小写的映射器

ObjectMapper om = new ObjectMapper();
om.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
return om;

为清楚起见,您可以在 POJO 中使用注释 (https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations)

   @JsonProperty("YourField")
   private String YourField;

注意:如果你想做一些 "Tolerant Reader" (http://martinfowler.com/bliki/TolerantReader.html) 的部分解析,你可能会发现基于 class 的注解 @JsonIgnoreProperties(ignoreUnknown = true) 所以如果你试图解析你没有描述的字段,你不会得到异常。