Jackson:将 json 解析为 Map<String, Object> 对于给定的 Map<String, Class<?>>



我得到了一个配置的杰克逊ObjectMapper实例,其中应用了一些模块、反序列化器和配置。

我还有一个"平面"json,这意味着要么没有内部节点,要么ObjectMapper能够将该内部节点解析为单个对象。

我想将给定的 json 解析为Map<String, Object>(属性名称 - 反序列化对象(。每个 json 属性名称的预期类是已知的,因此我可以将它们作为Map<String, Class<?>>传递。如何存档该目标?

这就像用jackson.reader().fotType(Pojo.class).readValue()解析到pojo,然后用反射收集pojo字段。但是我想避免提取 pojo 的类,避免使用反射并获取仅存在于 json 属性中的结果 Map。

受 Convert JsonNode to POJO 启发的解决方案:

  1. 将 json 解析为树
  2. 通过 treeToValue 将树子节点转换为预期的 Java 对象

片段:

public Map<String, Object> decode(String json, Map<String, Class<?>> propertyClasses) throws JsonProcessingException {
final HashMap<String, Object> parsedFields = new HashMap<>();
final Iterator<Map.Entry<String, JsonNode>> jsonNodes = jacksonReader.readTree(json).fields();
while (jsonNodes.hasNext()) {
final Map.Entry<String, JsonNode> jsonEntry = jsonNodes.next();
final String propertyName = jsonEntry.getKey();
final Class<?> propertyClass = propertyClasses.get(propertyName);
final Object parsedField = jacksonReader.treeToValue(jsonEntry.getValue(), propertyClass);
parsedFields.put(propertyName, parsedField);
}
return parsedFields;
}

最新更新