Skip to content

Commit

Permalink
provide the "ObjectMapper.treeToValue(TreeNode, TypeReference)" method (
Browse files Browse the repository at this point in the history
  • Loading branch information
fantasy0v0 committed Jul 27, 2023
1 parent 02b8ea8 commit fe23e05
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -3485,6 +3485,20 @@ public <T> T treeToValue(TreeNode n, JavaType valueType)
}
}

/**
* Same as {@link #treeToValue(TreeNode, JavaType)} but target type specified
* using fully resolved {@link TypeReference}.
*
* @since 2.16
*/
public <T> T treeToValue(TreeNode n, TypeReference<T> toValueTypeRef)
throws IllegalArgumentException,
JsonProcessingException
{
JavaType valueType = constructType(toValueTypeRef);
return treeToValue(n, valueType);
}

/**
* Method that is reverse of {@link #treeToValue}: it
* will convert given Java value (usually bean) into its
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import static org.junit.Assert.*;

import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.Assert;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
Expand Down Expand Up @@ -178,6 +179,17 @@ public void testTreeToValue() throws Exception
// ... also JavaType
r1 = mapper.treeToValue(root, mapper.constructType(Root.class));
assertEquals(13, r1.leaf.value);

// ... also TypeReference
r1 = mapper.treeToValue(root, new TypeReference<Root>() {});
assertEquals(13, r1.leaf.value);

JSON = "[{\"leaf\":{\"value\":13}}, {\"leaf\":{\"value\":12}}]";
root = mapper.readTree(JSON);
List<Root> array = mapper.treeToValue(root, new TypeReference<List<Root>>() {});
assertEquals(2, array.size());
assertEquals(13, array.get(0).leaf.value);
assertEquals(12, array.get(1).leaf.value);
}

// [databind#1208]: should coerce POJOs at least at root level
Expand Down

0 comments on commit fe23e05

Please sign in to comment.