I have an object with unknown values, say
{ "data": [ {"a":..., "dont_know_what_else_is_here":....} ] }
And I just want to store the value of "data" as a string into a variable/database.
How should I read it from the streaming API?
databind. ObjectMapper ) is the simplest way to parse JSON with Jackson. The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON.
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.
Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.
Reading JSON from a File Thankfully, Jackson makes this task as easy as the last one, we just provide the File to the readValue() method: final ObjectMapper objectMapper = new ObjectMapper(); List<Language> langList = objectMapper. readValue( new File("langs. json"), new TypeReference<List<Language>>(){}); langList.
Provided that you have already read this object into JsonNode
, you can do it like this:
String content = jsonNode.get("data").textValue();
UPD: since you're using a streaming parser, this example on Jackson usage might help.
UPD: the method name is now textValue() - docs
When we try to fetch data in form of string from JsonNode,we usually use asText, but we should use textValue instead.
asText: Method that will return a valid String representation of the container value, if the node is a value node (method isValueNode() returns true), otherwise empty String.
textValue: Method to use for accessing String values. Does NOT do any conversions for non-String value nodes; for non-String values (ones for which isTextual() returns false) null will be returned. For String values, null is never returned (but empty Strings may be)
So Let's take an example,
JsonNode getJsonData(){ ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("anyParameter",null); return node; } JsonNode node = getJsonData(); json.get("anyParameter").asText() // this will give output as "null" json.get("").textValue() // this will give output as null
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