java @Produces @Consumes 意思是 ... JSON 或者它只是一个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17817330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 15:06:35  来源:igfitidea点击:

@Produces @Consumes meaning ... JSON or it is just a String

javajsonrest

提问by flyer

Suppose we have some RESTful resource serving this POST:

假设我们有一些 RESTful 资源服务于这个 POST:

@POST
@Produces("application/json")
@Consumes("application/json")
public String doPostJson(String string) {
    ...
}

( I was able to run the above in my server so I am assuming this is a valid implementation )

(我能够在我的服务器中运行上述内容,所以我假设这是一个有效的实现)

Now I am thinking the doPostJson() gets String and returns String. This string could be something totally different than JSON valid string. Am I right? So what is the meaning of "application/json" if I can use any string here?

现在我在想 doPostJson() 获取 String 并返回 String。该字符串可能与 JSON 有效字符串完全不同。我对吗?那么如果我可以在这里使用任何字符串,那么“application/json”是什么意思?

MORE: In other hand, could I just use this?

更多:另一方面,我可以使用这个吗?

@POST
@Produces("text/plain")
@Consumes("text/plain")
public String doPostJson(String string) {
    ... /* read passed parameter as JSON valid string and return JSON string */
}

回答by Juned Ahsan

Producesand Consumesannotations are used for sharing theContent-Typeand Acceptheaders information respectively with your webservice users. Content-type header will help the receiver/consumer of your service, to treat the response as per the information in that header. If you mark the value of content-type header as application/json, then receiver can accordingly use a json parser. Similarly, using the Consumes, you are assuring that Accept header is application/json so that you can do the json parsing/unmarshalling accordingly.

ProducesConsumes注释分别用于与您的网络服务用户共享Content-TypeAccept标题信息。内容类型标头将帮助您的服务的接收者/消费者根据该标头中的信息处理响应。如果将 content-type 标头的值标记为 application/json,则接收方可以相应地使用 json 解析器。同样,使用 Consumes,您可以确保 Accept 标头是 application/json,以便您可以相应地进行 json 解析/解组。

回答by Zavior

"application/json" is the mime-type you are serving out, see this related question for some more details link. It helps the application communicating with your application. They might completely reject the response should it be of the wrong mimetype, for example image/jpeg instead of application/json

“application/json” 是您提供的 MIME 类型,有关更多详细信息链接,请参阅此相关问题。它有助于应用程序与您的应用程序通信。如果响应是错误的 mimetype,他们可能会完全拒绝响应,例如 image/jpeg 而不是 application/json