在Play 2中使用json

mst*_*ffo 4 json playframework playframework-2.0

我正在尝试创建一个简单的应用程序,允许我创建,读取,更新和删除各种用户.我有一个基本的基于UI的视图,控制器和模型,但希望比这更高级,并提供RESTful json接口.

然而,尽管阅读了我在Play 2文档,Play 2 Google组和stackoverflow网站上可以找到的所有内容,但我仍然无法使用它.

我已根据之前的反馈更新了我的控制器,现在我相信它是基于文档的.

这是我更新的控制器:

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

....
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,我收到以下错误:

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();
Run Code Online (Sandbox Code Playgroud)

据我所知,我已经从文档中复制了所以我将非常感谢帮助您实现这一目标.

mst*_*ffo 5

Json在Play 2文档中使用该类似乎存在冲突.为了使上面的示例正常工作,使用以下导入:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意明确调用正确的Json@BodyParser

我不确定这是不是一个bug?但这是我能让这个例子工作的唯一方法.