Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prettyPrint jsonNode in Play

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?

like image 615
fsperrle Avatar asked Mar 06 '14 10:03

fsperrle


People also ask

How do you find the value of JsonNode?

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.

What is the use of JsonNode?

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.

How do you declare JsonNode?

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);

What is the difference between ObjectNode and 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.


2 Answers

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);
like image 124
mantithetical Avatar answered Oct 05 '22 22:10

mantithetical


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)

like image 32
Glenn 'devalias' Grant Avatar answered Oct 05 '22 22:10

Glenn 'devalias' Grant