Reputation: 1377
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
Upvotes: 2
Views: 3419
Reputation: 13907
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);
Upvotes: 1