RESTful服务是否可以为同一资源返回JSON和XML,具体取决于请求标头? [英] Can a RESTful service return both JSON and XML for the same resource, depending on the request header?

查看:192
本文介绍了RESTful服务是否可以为同一资源返回JSON和XML,具体取决于请求标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的问题更多来自架构方面,而不是完全技术性问题。

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

RESTful服务是否应该以同时返回JSON和XML的方式设计?

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

据我所知,这是一种不好的做法,应该为此定义单独的资源。一个资源应该返回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.

我认为这是正确的吗?

推荐答案

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

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.

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

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


  1. 如果已将扩展添加到资源(<$ c) $ c> GET /user/1234.json 或 GET /user/1234.xml ),将其用作请求的格式。

  2. 如果设置了Accept标头,请使用该标头的值作为请求的格式。

  3. 如果有请求正文(如POST的情况) ,并且Content-Type标头指定JSON或XML,使用它。

  4. 如果以上都不适用,则使用默认格式(通常使用JSON作为默认格式,除非您的客户通常仍在使用XML)。

  1. If an extension has been added to the resource (GET /user/1234.json or 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).

这篇关于RESTful服务是否可以为同一资源返回JSON和XML,具体取决于请求标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆