danharper/laravel-jsonx

通过 JSONx 中间件为 JSON 说话的 Laravel API 添加 XML 支持

v0.1.2 2015-11-23 10:55 UTC

This package is auto-updated.

Last update: 2024-08-26 05:44:32 UTC


README

Latest Stable Version License

只需添加此中间件即可为您的 JSON API 添加 XML 支持。所有传入的 XML 请求都转换为 JSON。所有输出的 JSON 响应都转换为 XML。

请求只需要使用 Accept: application/xml 头来接收 XML 格式的响应。如果发送 XML,也需要使用 Content-Type: application/xml 头。

它使用 IBM 的标准将 JSON 表示为 XML:JSONx

这个库只是围绕 danharper/jsonx 的一个小包装。如果您不使用 Laravel,或者需要基于标准 PSR-7 消息的库,请查看 danharper/psr7-jsonx

安装

composer require danharper/laravel-jsonx

app/Http/Kernel 中的 $routeMiddleware 注册中间件

protected $routeMiddleware => [
  // ...
  'jsonx' => \danharper\LaravelJSONx\JSONxMiddleware::class,
];

然后将 jsonx 中间件添加到您的 API 路由中。

示例

中间件注册后,可以这样使用它

Route::get('foo', ['middleware' => ['jsonx'], 'uses' => function() {
  return [
    'fruits' => ['apple', 'banana', 'pear'],
    'something' => true,
  ];
});

创建一个 JSON 请求,例如使用 Accept: application/json 头,然后您将得到(如 Laravel 默认提供的)

{
  "fruits": ["apple", "banana", "pear"],
  "something": true
}

但是使用 Accept: application/xml 头创建 XML 请求,您将得到 JSONx

<?xml version="1.0" encoding="UTF-8"?>
<json:object xmlns:json="http://www.ibm.com/xmlns/prod/2009/jsonx" xsi:schemaLocation="http://www.datapower.com/schemas/json jsonx.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <json:array name="fruits">
    <json:string>apple</json:string>
    <json:string>banana</json:string>
    <json:string>pear</json:string>
  </json:array>
  <json:boolean name="something">true</json:boolean>
</json:object>

此外,传入的 XML 数据(格式化为 JSONx)将被无缝转换为 JSON。

例如,这两个是等效的(假设它们分别带有 Content-Type: application/jsonContent-Type: application/xml 头)

{
  "address": {
    "line1": "9 Long Street",
    "city": "Portsmouth"
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<json:object xmlns:json="http://www.ibm.com/xmlns/prod/2009/jsonx" xsi:schemaLocation="http://www.datapower.com/schemas/json jsonx.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <json:object name="address">
    <json:string name="line1">9 Long Street</json:string>
    <json:string name="city">Portsmouth</json:string>
  </json:object>
</json:object>

处理程序

Route::post('/', ['middleware' => ['jsonx'], 'uses' => function() {
  return [
    'hello' => request('address.city')
  ];
});

当请求为 JSON(默认)时,作为 Accept: application/json 或 XML 作为 Accept: application/xml 请求响应,响应将是

{
  "hello": "Portsmouth"
}
<?xml version="1.0" encoding="UTF-8"?>
<json:object xmlns:json="http://www.ibm.com/xmlns/prod/2009/jsonx" xsi:schemaLocation="http://www.datapower.com/schemas/json jsonx.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<json:string name="hello">Portsmouth</json:string>
</json:object>