简体   繁体   中英

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.

Also I have an "flat" json, meaning either no inner nodes, or ObjectMapper is able to parse that inner nodes to an single object.

I want to parse given json to Map<String, Object> (property name - deserialized object). Expected classes for each json property name are known, so I could pass them as 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. But I want to avoid extracting pojo's class, avoid using reflection and get in resulting Map only present in json properties.

Solution inspired by Convert JsonNode into POJO :

  1. Parse json to tree
  2. Convert tree subnodes to expected java objects via treeToValue

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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