Skip to content

Commit 265884a

Browse files
authored
README.md: add example treemodel heterogenous operations (#4135)
1 parent b2ab29c commit 265884a

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

README.md

+25
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,31 @@ with above, we end up with something like as 'json' String:
185185

186186
Tree Model can be more convenient than data-binding, especially in cases where structure is highly dynamic, or does not map nicely to Java classes.
187187

188+
Finally, feel free to mix and match, and even in the same json document (useful when only part of the document is known and modeled in your code)
189+
```java
190+
// Some parts of this json are modeled in our code, some are not
191+
JsonNode root = mapper.readTree(complexJson);
192+
Person p = mapper.treeToValue(root.get("person"), Person.class); // known single pojo
193+
List<Person> friends = mapper.treeToValue(root.get("friends"), new TypeReference<List<Person>>() { }); // generics
194+
Map<String, Object> dynamicmetadata = mapper.treeToValue(root.get("dynamicmetadata"), Map.class); // unknown smallish subfield, convert all to collections
195+
int singledeep = root.get("deep").get("large").get("hiearchy").get("important").intValue(); // single value in very deep optional subfield, ignoring the rest
196+
int singledeeppath = root.at("/deep/large/hiearchy/important").intValue(); // json path
197+
int singledeeppathunique = root.findValue("important").intValue(); // by unique field name
198+
199+
// Send an aggregate json from heterogenous sources
200+
ObjectNode root = mapper.createObjectNode();
201+
root.putPOJO("person", new Person("Joe")); // simple pojo
202+
root.putPOJO("friends", List.of(new Person("Jane"), new Person("Jack"))); // generics
203+
Map<String, Object> dynamicmetadata = Map.of("Some", "Metadata");
204+
root.putPOJO("dynamicmetadata", dynamicmetadata); // collections
205+
root.putPOJO("dynamicmetadata", mapper.valueToTree(dynamicmetadata)); // same thing
206+
root.set("dynamicmetadata", mapper.valueToTree(dynamicmetadata)); // same thing
207+
root.withObject("deep").withObject("large").withObject("hiearchy").put("important", 42); // create as you go
208+
root.withObjectProperty("deep").withObjectProperty("large").withObjectProperty("hiearchy").put("important", 42); // same but without trying json path
209+
root.withObject("/deep/large/hiearchy").put("important", 42); // json path
210+
mapper.writeValueAsString(root);
211+
```
212+
188213
## 5 minute tutorial: Streaming parser, generator
189214

190215
As convenient as data-binding (to/from POJOs) can be; and as flexible as Tree model can be, there is one more canonical processing model available: incremental (aka "streaming") model.

0 commit comments

Comments
 (0)