简体   繁体   English

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

[英]Jackson: parse json to Map<String, Object> for given Map<String, Class<?>>

I'm given a configured jackson's ObjectMapper instance with some modules, deserializers and configurations applied.我得到了一个配置好的 jackson 的ObjectMapper实例,其中应用了一些模块、解串器和配置。

Also I have an "flat" json, meaning either no inner nodes, or ObjectMapper is able to parse that inner nodes to an single object.此外,我有一个“平面”json,这意味着要么没有内部节点,要么ObjectMapper能够将该内部节点解析为单个对象。

I want to parse given json to Map<String, Object> (property name - deserialized object).我想将给定的 json 解析为Map<String, Object> (属性名称 - 反序列化对象)。 Expected classes for each json property name are known, so I could pass them as Map<String, Class<?>> .每个 json 属性名称的预期类都是已知的,因此我可以将它们作为Map<String, Class<?>>传递。 How could I archive that target?我怎么能存档那个目标?

It's like parsing with jackson.reader().fotType(Pojo.class).readValue() to pojo and then collecting pojo fields with reflection.这就像使用jackson.reader().fotType(Pojo.class).readValue()解析到 pojo 然后通过反射收集 pojo 字段。 But I want to avoid extracting pojo's class, avoid using reflection and get in resulting Map only present in json properties.但我想避免提取 pojo 的类,避免使用反射并获取仅存在于 json 属性中的结果 Map。

Solution inspired by Convert JsonNode into POJO :将 JsonNode 转换为 POJO启发的解决方案:

  1. Parse json to tree将 json 解析为树
  2. Convert tree subnodes to expected java objects via treeToValue通过 treeToValue 将树子节点转换为预期的 java 对象

Snippet:片段:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM