简体   繁体   English

玩!框架返回json响应

[英]Play! Framework return json response

I`m using Play! 我正在使用Play! Framework 2.0 and I'm new in this framework. Framework 2.0和我在这个框架中是新手。 How can I return just a json representation of my model in white html page? 如何在白色html页面中只返回我的模型的json表示?

What I'm doing is 我正在做的是

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

But I get Error : Cannot use a method returning Unit as an Handler 但我得到错误:无法使用返回Unit作为处理程序的方法

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

The method you are using is from Play 1.x, it is slightly different in Play 2.0. 您使用的方法来自Play 1.x,它在Play 2.0中略有不同。 From the documentation, here is an example of how to reply to a sayHello JSON request 从文档中,这是一个如何回复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);
  }
}

The important part of this from what you are asking is the return ok(result) which returns a JSON ObjectNode . 你要问的重要部分是return ok(result)返回一个JSON ObjectNode

Create a new Model from your list: 从列表中创建一个新模型:

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
}

In the Business.java class I have a static variable: 在Business.java类中,我有一个静态变量:

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

This will display the JSON object on localhost:9000/getBusinesses after you add the route: 在添加路由后,这将在localhost:9000 / getBusinesses上显示JSON对象:

GET      /getBusinesses   controllers.Application.getBusinesses()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM