I'm just starting using the Jackson JSON library. Jackson is a very powerful library, but it has a terribly extensive API. A lot of things can be done in multiple ways. This makes it hard to find your way in Jackson - how to know what is the correct/best way of doing things?
Why would I use this solution:
String json = "{\"a\":2, \"b\":\"a string\", \"c\": [6.7, 6, 5.6, 8.0]}"; ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readValue(json, JsonNode.class); if (node.isObject()) { ObjectNode obj = mapper.convertValue(node, ObjectNode.class); if (obj.has("a")) { System.out.println("a=" + obj.get("a").asDouble()); } }
Over a solution like this:
String json = "{\"a\":2, \"b\":\"a string\", \"c\": [6.7, 6, 5.6, 8.0]}"; ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(json); if (node.isObject()) { ObjectNode obj = (ObjectNode) node; if (obj.has("a")) { System.out.println("a=" + obj.get("a").asDouble()); } }
Or over solutions that I came across using JsonFactory and JsonParser and maybe even more options...
It seems to mee that mapper.readValue is most generic and can be used in a lot of cases: read to JsonNode, ObjectNode, ArrayNode, PoJo, etc. So why would I want to use mapper.readTree?
And what is the best way to convert a JsonNode to an ObjectNode? Just cast to ObjectNode? Or use something like mapper.convertValue?
The simple readValue API of the ObjectMapper is a good entry point. We can use it to parse or deserialize JSON content into a Java object. Also, on the writing side, we can use the writeValue API to serialize any Java object as JSON output.
JsonNode represents any valid Json structure whereas ObjectNode and ArrayNode are particular implementations for objects (aka maps) and arrays, respectively.
ObjectNode is a concrete implementation of JsonNode that maps a JSON object, and a JSON object is defined as following: An object is an unordered set of name/value pairs.
ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model ( JsonNode ), as well as related functionality for performing conversions.
readValue() can be used for any and all types, including JsonNode
. readTree() only works for JsonNode
(tree model); and is added for convenience.
Note that you NEVER want to use your first example: it is equivalent to writing out your node as JSON, then reading it back -- just cast it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With