Jackson 2.7.0 on Android
Hi, I need to cast a TreeNode into model list
why ObjectMapper.treeToValue(TreeNode, TypeReference) is missing ?
Due to number of permutations, some combinations may be missing. Whether those should be added is an open question; in the meantime what you need to do is to create JavaType out of TypeReference (this is what is done internally anyway):
mapper.treeToValue(node, mapper.getTypeFactory().constructType(typeRef));
// or perhaps there is `ObjectMapper.constructType(TypeReference)` for short cut
The method in ObjectMapper is:
public <T> T treeToValue(TreeNode n, Class<T> valueType)
(https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java#L2575)
Maybe I've missed something very obvious but the JavaType returned from the TypeFactory cannot be passed in for the second parameter as type Class and there are no other overloads of treeToValue in ObjectMapper.
mapper.treeToValue(node, mapper.getTypeFactory().constructType(typeRef));
Instead we ended up using readValue:
mapper.readValue(
mapper.treeAsTokens(node),
mapper.getTypeFactory().constructType(typeRef));
Other than a few shortcuts provided by treeToValue this is the logic it uses. If this is indeed correct, I would be happy to submit a PR for adding the type reference variant.
@vjkoskela
yes, that is exactly what I finally used:
JavaType jt = mapper.getTypeFactory().constructType(type);
return mapper.readValue(mapper.treeAsTokens(node), jt);
Most helpful comment
The method in ObjectMapper is:
(https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java#L2575)
Maybe I've missed something very obvious but the JavaType returned from the TypeFactory cannot be passed in for the second parameter as type Class and there are no other overloads of treeToValue in ObjectMapper.
Instead we ended up using readValue:
Other than a few shortcuts provided by treeToValue this is the logic it uses. If this is indeed correct, I would be happy to submit a PR for adding the type reference variant.