Using json with Play 2

21,096

Solution 1

There appear to be conflicts in the use of the Json class in the Play 2 documentation. To get the example above working correctly, the following imports are used:

import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.BodyParser;                     
import play.libs.Json;
import play.libs.Json.*;                        

import static play.libs.Json.toJson;

import org.codehaus.jackson.JsonNode;           
import org.codehaus.jackson.node.ObjectNode;    

@BodyParser.Of(play.mvc.BodyParser.Json.class)
public static index sayHello() {
    JsonNode json = request().body().asJson();
    ObjectNode result = Json.newObject();
    String name = json.findPath("name").getTextValue();
    if(name == null) {
        result.put("status", "KO");
        result.put("message", "Missing parameter [name]");
        return badRequest(result);
    } else {
        result.put("status", "OK");
        result.put("message", "Hello " + name);
        return ok(result);
    }
}

Note the explicit calling of the right Json class in @BodyParser

I'm not sure if this is a bug or not? But this is the only way I could get the example to work.

Solution 2

Import those two

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

According to this documentation: http://fasterxml.github.io/jackson-databind/javadoc/2.0.0/com/fasterxml/jackson/databind/node/ObjectNode.html

Solution 3

Try this:

import play.*;
import play.mvc.*;
import org.codehaus.jackson.JsonNode; //Fixing "error: cannot find symbol" for JsonNode

// Testing JSON
  @BodyParser.Of(BodyParser.Json.class) //Or you can import play.mvc.BodyParser.Json
  public static Result sayHello() {
    JsonNode json = request().body().asJson();
    String name = json.findPath("name").getTextValue();
    if(name==null) {
      return badRequest("Missing parameter [name]");
    } else {
      return ok("Hello " + name);
    }
  }

Solution 4

AFAIK, the code you are using has not reached any official Play version (neither 2.0 or 2.0.1) according to this: https://github.com/playframework/Play20/pull/212

Instead, you can do this (not tested):

if(request().getHeader(play.mvc.Http.HeaderNames.ACCEPT).equalsIgnoreCase("application/json")) {
Share:
21,096
mstreffo
Author by

mstreffo

Family, tech, squash, ultra runner in the making, apprentice magician! Trying to be awesome!! Update: Now I also try to code with Play 2 and Angular JS!!

Updated on July 05, 2022

Comments

  • mstreffo
    mstreffo almost 2 years

    I'm trying to create a simple application that allows me to create, read, update and delete various users. I have a basic UI-based view, controller and model that work, but wanted to be more advanced than this and provide a RESTful json interface.

    However, despite reading everything I can find in the Play 2 documentation, the Play 2 Google groups and the stackoverflow website, I still can't get this to work.

    I've updated my controller based on previous feedback and I now believe it is based on the documentation.

    Here is my updated controller:

    package controllers;
    
    import models.Member;
    
    import play.*;
    import play.mvc.*;
    import play.libs.Json;
    import play.data.Form;
    
    public class Api extends Controller {
    
    /* Return member info - version to serve Json response */
    public static Result member(Long id){
      ObjectNode result = Json.newObject();
      Member member = Member.byid(id);
        result.put("id", member.id);
        result.put("email", member.email);
        result.put("name", member.name);
        return ok(result);
    }
    
    // Create a new body parser of class Json based on the values sent in the POST
    @BodyParser.Of(Json.class)
    public static Result createMember() {
        JsonNode json = request().body().asJson();
        // Check that we have a valid email address (that's all we need!)
        String email = json.findPath("email").getTextValue();
        if(name == null) {
            return badRequest("Missing parameter [email]");
        } else {
            // Use the model's createMember class now
            Member.createMember(json);
            return ok("Hello " + name);
        }
    }
    
    ....
    

    But when I run this, I get the following error:

    incompatible types [found: java.lang.Class<play.libs.Json>] [required: java.lang.Class<?extends play.mvc.BodyParser>]
    In /Users/Mark/Development/EclipseWorkspace/ms-loyally/loyally/app/controllers/Api.java at line 42.
    
    41  // Create a new body parser of class Json based on the values sent in the POST
    42  @BodyParser.Of(Json.class) 
    43  public static Result createMember() {
    44      JsonNode json = request().body().asJson();
    45      // Check that we have a valid email address (that's all we need!)
    46      String email = json.findPath("email").getTextValue();
    

    As far as I can tell, I've copied from the documentation so I would appreciate any help in getting this working.