Play Framework: Returning JSON Responses

06 Apr 2014

I've recently started a project at working using the Play Framework and while its a great framework, I was having a lot of trouble with some of the simplest tasks. I wouldn't blame Play for my problems, returning to Java after a long hiatus, being spoiled by dynamicly typed languages, and lack of documentation really made such tasks like returning a JSON response difficult.

I figured that I may not be the only in this position, judging by the questions in the IRC channel and lack of responses, I figured it may be a good idea to jot down some of my notes, not only for myself, my coworkers, but for all my fellow Play framework noobs. Apologies for the introduction, I'll try to keep the rest of this posts and the futures, short, succinct, and to the point.

tl;dr

Use ObjectNode class found in the com.fasterxml.jackson.databind.node.ObjectNode package.

import com.fasterxml.jackson.databind.node.ObjectNode;

    ObjectNode response = Json.newObject();
    response.put("status", 200);
    response.put("message", "Request was successful");
    response.put("data", Json.toJson(users));
    return ok(response);

Using ObjectNode

To easily return mixed response types, I suggest using the ObjectNode class found in the com.fasterxml.jackson.databind.node.ObjectNode package. Using the class is simple, first instantiate an object:

ObjectNode response = Json.newObject();

From there, you can treat the object similar to a map but using put() function.

response.put("status", 200);
    response.put("message", "Request was successful");

Often times we want to return an object or array of objects. Using the Json.toJson() function found in play.libs.Json we can easily convert objects or lists of objects to be included in our JSON response.

response.put("data", Json.toJson(users));

Finally, you'll probably want to use the static return response methods to easily return our JSON response.

return ok(response);