2012-06-23 72 views
10

我使用Play! Framework 2.0和我在这个框架中是新的。我怎样才能返回我的模型的JSON表示在白色的HTML页面?玩!框架返回json响应

我在做什么是

public static void messagesJSON(){ 
    List<Message> messages = Message.all(); 
    renderJSON(messages); 
} 

,但我得到错误:无法使用返回单位为处理器

回答

10

您所使用的方法是从播放1.x的一种方法,它稍Play 2.0中有所不同。从文档,这里是如何从你所问的是,它返回一个JSON ObjectNodereturn ok(result)回复sayHello JSON请求

@BodyParser.Of(Json.class) 
public static Result sayHello() { 
    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); 
    } 
} 

这样做的重要组成部分,一个例子。

+0

这是什么意思“索引”作为返回类型?在我看来,编译器不明白它,@BodyParser也错误(类型不匹配)这个代码适合你吗?或者你能否显示进口和更多更广泛的可供参考的情况。 – Stas

+1

@Stas,源文档中存在拼写错误,它应该在Play 2.0控制器中返回'Result'作为每个'action'。 – biesior

+0

好点@马库斯。并感谢您更新Github上的文档。 – Codemwnci

37

如何 return ok(Json.toJson(Moments.all());

+4

这是一个非常有用的答案,因为它会自动将整个对象图呈现为json - 而不是像文档中所示的那样手动构建json对象。 – prule

+0

我相信你也可以通过Jackson注释来定制JSON结构。 – Sudhir

+0

添加类参考: – Alex

2

创建一个从您的列表中的新型号:

public static Result getBusinesses(){ 
    List<Business> businesses = new Model.Finder(String.class, Business.class).all(); 
    return ok(Json.toJson(businesses)); //displays JSON object on empty page 
} 

在Business.java类我有一个静态变量:

public static Finder<Long,Business> find = new Finder(Long.class, Business.class); 

这将显示添加路由后,在localhost上的JSON对象:9000/getBusinesses :

GET  /getBusinesses controllers.Application.getBusinesses()