Java RESTful 服务能否根据请求标头为同一资源同时返回 JSON 和 XML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22362607/
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-08-13 15:15:59  来源:igfitidea点击:

Can a RESTful service return both JSON and XML for the same resource, depending on the request header?

javaxmljsonrestrestful-architecture

提问by Nital

I have a simple RESTful method which currently returns JSON representation of an object.

我有一个简单的 RESTful 方法,它当前返回对象的 JSON 表示。

My question is more of from the architectural perspective and not completely technical.

我的问题更多是从架构的角度而不是完全技术性的。

Should a RESTful service be designed in such a way that it returns both JSON and XML at the same time?

是否应该将 RESTful 服务设计为同时返回 JSON 和 XML?

As far as I know this is a bad practice and separate resources should be defined for this. One resource should return JSON data and other one XML.

据我所知,这是一种不好的做法,应该为此定义单独的资源。一种资源应返回 JSON 数据,另一种应返回 XML。

Am I thinking it correctly?

我的想法正确吗?

采纳答案by Mike Dunker

The same resource may return either XML or JSON depending upon the request, but it shouldn't return both at the same time. You will know which one to return based upon the request, so there is no need to generate both -- just generate the one you'll be returning.

同一个资源可能会根据请求返回 XML 或 JSON,但不应同时返回两者。您将根据请求知道要返回哪一个,因此无需同时生成两者——只需生成您将要返回的那个。

Here is how you might choose to decide which to return. Evaluate in order, stopping when you've determined the format to return:

以下是您可以选择决定返回哪个的方式。按顺序评估,当您确定要返回的格式时停止:

  1. If an extension has been added to the resource (GET /user/1234.jsonor GET /user/1234.xml), use that as the requested format.
  2. If an Accept header is set, use that header's value as the requested format.
  3. If there is a request body (as in the case of a POST), and the Content-Type header specifies JSON or XML, use that.
  4. Use a default format if none of the above apply (generally use JSON as your default unless your customers are generally still using XML).
  1. 如果已将扩展添加到资源(GET /user/1234.jsonGET /user/1234.xml),请将其用作请求的格式。
  2. 如果设置了 Accept 标头,则使用该标头的值作为请求的格式。
  3. 如果有请求正文(如 POST 的情况),并且 Content-Type 标头指定 JSON 或 XML,请使用它。
  4. 如果以上都不适用,则使用默认格式(通常使用 JSON 作为默认格式,除非您的客户通常仍在使用 XML)。

回答by Plínio Pantale?o

No. The way you represent your resource should be defined by what your clients expect (there is a http-header to say what representations the client accept). This means your server should check what is the representation the current client accepts and send the response in this representation (or send a response that says he cannot represent the resource in that media-type)

不。您表示资源的方式应该由您的客户期望的方式定义(有一个 http-header 来说明客户端接受什么表示)。这意味着您的服务器应该检查当前客户端接受的表示形式并在此表示形式中发送响应(或发送一个响应,表示他不能表示该媒体类型中的资源)