簡體   English   中英

玩!框架返回json響應

[英]Play! Framework return json response

我正在使用Play! Framework 2.0和我在這個框架中是新手。 如何在白色html頁面中只返回我的模型的json表示?

我正在做的是

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

但我得到錯誤:無法使用返回Unit作為處理程序的方法

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

您使用的方法來自Play 1.x,它在Play 2.0中略有不同。 從文檔中,這是一個如何回復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);
  }
}

你要問的重要部分是return ok(result)返回一個JSON ObjectNode

從列表中創建一個新模型:

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:9000 / getBusinesses上顯示JSON對象:

GET      /getBusinesses   controllers.Application.getBusinesses()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM