I'm writing a typical Play Framework app where I want to return a JsonNode from my Controller's methods, using Jackson.
This is how I'm doing it right now:
public static Result foo() {
MyPojoType myPojo = new myPojo();
String tmp = new ObjectMapper().writerWithView(JSONViews.Public.class).writeValueAsString(myPojo);
JsonNode jsonNode = Json.parse(tmp);
return ok(jsonNode);
}
Is it possible to avoid the "String tmp" copy and convert directly from MyPojoType to JsonNode using a view?
Maybe I can use ObjectMapper.valueToTree, but I don't know how to specify a JSonView to it.
The ObjectMapper class provided by Jackson API provides functionality for converting between Java Objects and JSON. If you are using Maven as a build tool in your project, then add the following dependency in your pom.xml file. Convert POJO to JSON and vice versa using Jackson API...!!!
To convert an instance of JsonNode to a Java Object, you can use the treeToValue () method from ObjectMapper: Read the guide Working with Tree Model Nodes in Jackson for more JsonNode examples. For more Jackson examples, check out the How to read and write JSON using Jackson in Java tutorial.
If your JSON input in has more properties than your POJO has and you just want to ignore the extras in Jackson 2.4, you can configure your ObjectMapper as follows. This syntax is different from older Jackson versions.
The JSON format is one of the most popular ways to serialize data. Knowing how to read and write it is an important skill for any programmer. There are a couple of Java libraries that can parse JSON, but in this tutorial, we'll focus on an open-source project developed by Google called GSON.
Interesting question: off-hand, I don't think there is a specific method, and your code is the most straight-forward way to do it: valueToTree
method does not apply any views.
So code is fine as is.
After more investigation, this is what I did in the end to avoid the redundant work:
public Result toResult() {
Content ret = null;
try {
final String jsonpayload = new ObjectMapper().writerWithView(JsonViews.Public.class).writeValueAsString(payload);
ret = new Content() {
@Override public String body() { return jsonpayload; }
@Override public String contentType() { return "application/json"; }
};
} catch (JsonProcessingException exc) {
Logger.error("toResult: ", exc);
}
if (ret == null)
return Results.badRequest();
return Results.ok(ret);
}
In summary: The methods ok, badRequest, etc accept a play.mvc.Content class. Then, simply use it to wrap your serialized json object.
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