gpt4 book ai didi

java - 玩! 2+ 以 RESTfull 方式添加 JSON 支持

转载 作者:行者123 更新时间:2023-12-01 05:06:34 25 4
gpt4 key购买 nike

我习惯做ROR,但我需要在Java环境中制作一个RESTfull WebService。所以我决定用 Play 来尝试一下!因为它看起来确实是个好主意。

所以我试图找到一种方法将 JSON 添加到我已经存在的第一个应用程序中,按照这些指令完成:http://www.playframework.org/documentation/2.0.3/JavaTodoList

我想要的是与 ROR 类似的工作方式。至少,我希望能够通过以下方式请求 JSON 支持:

  • 调用 .json 网址
  • 使用“接受:application/json” header
<小时/>

所以我尝试了一些类似的肮脏的事情:

    JsonNode json = request().body().asJson();
if(json != null) {
return ok(Json.toJson(Task.all()));
}

return ok(
views.html.index.render(Task.all(), taskForm)
);

而且它现在显然不起作用......

<小时/>

我需要检测客户端需要哪种类型。我看到有些人添加了这样的脏路由:

    POST    /bars                                       BarController.index()
GET /bars.json BarController.indexJSON()

但是它显然不支持客户端使用 header 来指定 json 请求...

<小时/>

所以,我需要的是某种方法来查明是否有任何指定内容类型或接受 application/json 的 header 。如果是这样,BarController.index() 将返回 BarController.indexJSON()...

总而言之,它与 ROR 非常相似:

respond_to do |format|
format.html # index.html.erb
format.json { render json: @bars }
end
<小时/>

总而言之:

有人经历过与我相同的推理并达到目的吗?

最佳答案

所以我通过使用 Controller 中的函数解决了我的问题,如下所示:

public static Result index()
public static Result indexJSON()

然后我添加了路线:

GET     /tasks                      controllers.TaskController.index()
GET /tasks/json controllers.TaskController.indexJSON()

我更喜欢task.json,但它不允许/tasks/:id.json ...

对于 header 支持,如果没有 header ,您需要检查经典函数:

public static Result index() {
if (request().getHeader(play.mvc.Http.HeaderNames.ACCEPT).equalsIgnoreCase("application/json") || request().getHeader(Http.HeaderNames.CONTENT_TYPE).equalsIgnoreCase("application/json")) {
return indexJSON();
}
else {
return ok(
views.html.index.render(Task.all(), taskForm)
);
}
}

结束了,各位!

有人有更好的解决方案吗?我不太喜欢这个...因为我会重复很多代码...

关于java - 玩! 2+ 以 RESTfull 方式添加 JSON 支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12576179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com