Thanks a lot, you make it clear, lol 在2020年6月20日星期六 UTC+8 上午2:05:32<Tatu Saloranta> 写道:
> On Fri, Jun 19, 2020 at 10:56 AM nU8K <[email protected]> wrote: > > > > anyway, here's the answer of "What's the difference between "get" and > "with" function", just check the source code implementation. > > Actually I would suggest looking at Javadocs (either from sources), or > if using IDE just look at definition. > > There is also `path()` that is distinct from `get()`, as well as > `with()`, but `with()` is meant when changing things: it guarantees > that path you have will exist in `ObjectNode` / `ArrayNode` (fails for > other nodes). > > So, you can do, for example: > > ObjectNode root = mapper.createObjectNode(); > root.with("branch").with("leaf").put("value", 42); > > and now ObjectNode structure describes > > { > "branch" : { > "leaf" : { > "value" : 42 > } > } > } > > conversely, `path()` allows traversal through "missing" nodes without > error: for missing nodes, there will > be `MissingNode` instance that never resolves to anything. So you can call > > JsonNode root = mapper.readTree(source); > JsonNode maybeValue = root.path("branch").path("leaf").path("value"); > assertTrue(maybeValue.isMissingValue()); > > even if incoming JSON was > > { } > > whereas trying to use `get()` would give a NullPointerException (since > `node.get("property") returns `null` if no such property exists). > There is also convenience alternative `at()` which takes `JsonPointer` > for simpler access: > > JsonNode maybeValue = root.at("/branch/leaf/value"); > > I hope this helps, > > -+ Tatu +- > > > > > ```java > > @Override > > public JsonNode get(String fieldName) { > > return _children.get(fieldName); > > } > > > > @Override > > public ObjectNode with(String propertyName) { > > JsonNode n = _children.get(propertyName); > > if (n != null) { > > if (n instanceof ObjectNode) { > > return (ObjectNode) n; > > } > > throw new UnsupportedOperationException("Property '" + propertyName > > + "' has value that is not of type ObjectNode (but " + n > > .getClass().getName() + ")"); > > } > > ObjectNode result = objectNode(); > > _children.put(propertyName, result); > > return result; > > } > > ``` > > > > -- > > You received this message because you are subscribed to the Google > Groups "jackson-user" group. > > To unsubscribe from this group and stop receiving emails from it, send > an email to [email protected]. > > To view this discussion on the web visit > https://groups.google.com/d/msgid/jackson-user/fe8fd7af-a8df-4a56-8e44-b5d1906cd118n%40googlegroups.com > . > -- You received this message because you are subscribed to the Google Groups "jackson-user" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/jackson-user/75fa6ea5-50ef-4da6-994f-457281cf1093n%40googlegroups.com.
