Skip to content

Commit fe23e05

Browse files
authored
provide the "ObjectMapper.treeToValue(TreeNode, TypeReference)" method (#4046) (#4056)
1 parent 02b8ea8 commit fe23e05

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3485,6 +3485,20 @@ public <T> T treeToValue(TreeNode n, JavaType valueType)
34853485
}
34863486
}
34873487

3488+
/**
3489+
* Same as {@link #treeToValue(TreeNode, JavaType)} but target type specified
3490+
* using fully resolved {@link TypeReference}.
3491+
*
3492+
* @since 2.16
3493+
*/
3494+
public <T> T treeToValue(TreeNode n, TypeReference<T> toValueTypeRef)
3495+
throws IllegalArgumentException,
3496+
JsonProcessingException
3497+
{
3498+
JavaType valueType = constructType(toValueTypeRef);
3499+
return treeToValue(n, valueType);
3500+
}
3501+
34883502
/**
34893503
* Method that is reverse of {@link #treeToValue}: it
34903504
* will convert given Java value (usually bean) into its

src/test/java/com/fasterxml/jackson/databind/node/TestConversions.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import static org.junit.Assert.*;
1010

11+
import com.fasterxml.jackson.core.type.TypeReference;
1112
import org.junit.Assert;
1213

1314
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@@ -178,6 +179,17 @@ public void testTreeToValue() throws Exception
178179
// ... also JavaType
179180
r1 = mapper.treeToValue(root, mapper.constructType(Root.class));
180181
assertEquals(13, r1.leaf.value);
182+
183+
// ... also TypeReference
184+
r1 = mapper.treeToValue(root, new TypeReference<Root>() {});
185+
assertEquals(13, r1.leaf.value);
186+
187+
JSON = "[{\"leaf\":{\"value\":13}}, {\"leaf\":{\"value\":12}}]";
188+
root = mapper.readTree(JSON);
189+
List<Root> array = mapper.treeToValue(root, new TypeReference<List<Root>>() {});
190+
assertEquals(2, array.size());
191+
assertEquals(13, array.get(0).leaf.value);
192+
assertEquals(12, array.get(1).leaf.value);
181193
}
182194

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

0 commit comments

Comments
 (0)