简体   繁体   中英

jackson: deserialize json to java map, ignore some entries

I've got json like this:

{
  "shouldBeIgnored1": "string",
  "shouldBeIgnored2": "string",
  "key1": {
             "id": 1,
             "value": "value"  
           },
  "key2": {
             "id": 2,
             "value": "another value"  
           }
    ...
}

and class Item :

class Item {
    private int id;
    private String value;

    //getters setters
}

Is there any simple way to deserialize that json to Map < String, Item > ? Not Item objects should be ignored.

Standard approach fails with

JsonMappingException: Can not instantiate value of type [simple type, class Item] from String value ('string'); no single-String constructor/factory method

One possible solution could be to preprocess the parsed JSON object before deserializing it into a Map.

First of all you would parse the JSON into an ObjectNode :

String json = "...";
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode objectNode = (ObjectNode) objectMapper.readTree(json);

You can then iterate over the fields of the ObjectNode , keeping track of which fields are not items and should therefore be removed:

Iterator<Map.Entry<String, JsonNode>> fields = objectNode.fields();
Set<String> fieldsToRemove = new HashSet<>();
while (fields.hasNext()) {
    Map.Entry<String, JsonNode> field = fields.next();
    String fieldName = field.getKey();
    JsonNode fieldValue = field.getValue();
    if (!fieldValue.isObject()) {
        fieldsToRemove.add(fieldName);
    }
}

Note that it is possible to apply a more strict condition on the fields here. I have just filtered out any fields that are not objects.

You can then remove these fields from the ObjectNode :

objectNode.remove(fieldsToRemove);

And finally deserialize the ObjectNode into a Map :

TypeReference<Map<String, Item>> typeReference = new TypeReference<Map<String, Item>>() {};
Map<String, Item> map = objectMapper.convertValue(objectNode, typeReference);

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