Via the Play WS API I get() a Response object. As it contains JSON I call
response.asJson()
which works perfectly fine. Now I want to return this JSON in a prettyprinted version so I tried to call
Json.prettyPrint(response.asJson())
However this does not work because prettyPrint expects a JsValue, not a JsonNode. So the question is how to convert a JsonNode to a JsObject?
We can access a field, array or nested object using the get() method of JsonNode class. We can return a valid string representation using the asText() method and convert the value of the node to a Java int using the asInt() method of JsonNode class.
The JsonNode class represents a node in the JSON tree model. It can express JSON data in the following data types: Array, Binary, Boolean, Missing, Null, Number, Object, POJO, String. These data types are defined in the JsonNodeType enum.
Write JsonNode to JSON Here is an example of writing a JsonNode to JSON: ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = readJsonIntoJsonNode(); String json = objectMapper. writeValueAsString(jsonNode);
JsonNode is a base class that ObjectNode and ArrayNode extend. JsonNode represents any valid Json structure whereas ObjectNode and ArrayNode are particular implementations for objects (aka maps) and arrays, respectively.
I am guessing you are using Play with Java. Instead of converting to JsValue, you could do something like:
JsonNode node = response.asJson();
ObjectMapper mapper = new ObjectMapper();
String pretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node);
Pull request #2924 (Currently only available in master as of 2014-05-26) improves Play Framework to allow converting between JsValue and JsonNode, etc.
As far as I know there still isn't a prettyPrint in the Java Json package, but this is one step closer.
Pretty print and some other functions (to bring the Java in line with the Scala) added in #2945 (Currently only available in master as of 2014-05-28)
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