Using json with Play 2

泪湿孤枕 提交于 2019-12-21 19:28:23

问题


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.


回答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.




回答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




回答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);
    }
  }



回答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")) {



回答5:


Did you try checking out the documentation for it?

Serving a JSON response looks like:

@BodyParser.Of(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);
  }
}



回答6:


You have imported play.libs.Json and then use the BodyParser.Of annotation with this Json.class.

The above annotation expects a class which extends a play.mvc.BodyParser. So simply replace @BodyParser.Of(Json.class) by @BodyParser.Of(BodyParser.Json.class).



来源:https://stackoverflow.com/questions/10471182/using-json-with-play-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!