简体   繁体   English

从 Play Framework 控制器返回 JSON 字符串

[英]Return JSON string from Play Framework controller

I am making an ajax POST request from the client.我正在从客户端发出 ajax POST 请求。 My Play Framework controller makes a request to a cross domain server which returns JSON.我的 Play Framework 控制器向返回 JSON 的跨域服务器发出请求。 I then want to forward this JSON to the client.然后我想将此 JSON 转发给客户端。 When I call Promise<JsonNode>.toString() , It appears I receive a memory address.当我调用Promise<JsonNode>.toString() ,我似乎收到了一个内存地址。 How can I get the actual JSON back to the client?如何将实际的 JSON 返回给客户端?

    public static Result addVenue() {

      final Map<String, String[]> values = request().body().asFormUrlEncoded();
      String queryString = values.get("venueName")[0]  + ",+" + values.get("venueAddress")[0] + ",+" + values.get("venueCity")[0] + ",+" + values.get("venueState")[0] + "+" + values.get("venueZip")[0];
      String queryURL = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" + queryString + "&key=" + "AIzaSyD1xSgKUnEZ_tM7qzcEAeM-SJBxPFhIpaU";
      queryURL = queryURL.replaceAll(" ", "+");

      Promise<JsonNode> jsonPromise = WS.url(queryURL).get().map(
              new Function<WSResponse, JsonNode>() {
                  public JsonNode apply(WSResponse response) {
                      JsonNode json = response.asJson();
                      return json;
                  }
              }
      );

      response().setHeader("Access-Control-Allow-Origin", "*");
      response().setHeader("Allow", "*");
      response().setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
      response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent");
      return ok(jsonPromise.toString());
}

Return a promise of result instead:改为返回结果承诺:

public static Promise<Result> addVenue() {
    return WS.url(URL).get().map((response) -> {
        return ok(response.asJson());
    });
}

I was finally able to return the JSON using the following code.我终于能够使用以下代码返回 JSON。 My implementation is a little different than another answer provided.我的实现与提供的另一个答案略有不同。 I will provide it just in case the other one doesn't work for some people.我会提供它以防万一另一个对某些人不起作用。

 final Promise<Result> resultPromise = WS.url(queryURL).get().map(
            new Function<WSResponse, Result>() {
                public Result apply(WSResponse response) {
                    Logger.info(response.asJson().toString());
                    return ok(response.asJson().toString());
                }
            }
 );
 return resultPromise;

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

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