我想知道如何将 ApiProblem 响应设置为默认的漂亮打印 Json。
2 回答
ZF-Hal 中有一个HalJsonStrategy
用于渲染。此策略扩展了默认 ZF2JsonStrategy
。此策略呈现HalJsonModel
扩展默认 ZF2JsonModel
类的类型的视图模型。渲染发生在HalJsonRenderer
扩展默认 ZF2JsonRenderer
类的情况下。
您可以通过将渲染策略更改为某些自定义策略或通过在HalJsonStrategy
.
不知道什么是最好的方法。
由于所有这些 hal-json 渲染逻辑都构建在默认的 ZF2 json 渲染逻辑之上,因此很可能通过更改配置来更改当前渲染器输出 json 的方式,就像您通常在 ZF2 中所做的那样,以实现漂亮打印输出。
也许这里的这个页面会帮助你实现你想要的。
概括:
它归结为将类中方法中的Json::encode
调用(或渲染调用)交换为render
JsonRenderer
Json::prettyPrint
注意: 这样做的原因可能是为了在浏览器窗口中以可读的方式查看 json 代码。有许多 json 插件可以帮助您解决这个问题,这将是一个更简单的解决方案。
我对 class 做了一些更改ApiProblemResponse
。我将属性设置$jsonFlags
为128,这与JSON_PRETTY_PRINT
代码有关。
这是我的更改的完整课程代码:
<?php
namespace Zend\ApiProblem;
use Zend\Http\Response;
/**
* Represents an ApiProblem response payload
*/
class ApiProblemResponse extends Response
{
/**
* @var ApiProblem
*/
protected $apiProblem;
/**
* Flags to use with json_encode JSON_PRETTY_PRINT
*
* @var int
*/
protected $jsonFlags = 128;
/**
* @param ApiProblem $apiProblem
*/
public function __construct(ApiProblem $apiProblem)
{
$this->apiProblem = $apiProblem;
$this->setCustomStatusCode($apiProblem->status);
$this->setReasonPhrase($apiProblem->title);
// Just comment/remove these lines to prevent flags from being overwrited
//if (defined('JSON_UNESCAPED_SLASHES')) {
//$this->jsonFlags = constant('JSON_UNESCAPED_SLASHES');
//}
}
/**
* @return ApiProblem
*/
public function getApiProblem()
{
return $this->apiProblem;
}
/**
* Retrieve the content
*
* Serializes the composed ApiProblem instance to JSON.
*
* @return string
*/
public function getContent()
{
return json_encode($this->apiProblem->toArray(), $this->jsonFlags);
}
/**
* Retrieve headers
*
* Proxies to parent class, but then checks if we have an content-type
* header; if not, sets it, with a value of "application/problem+json".
*
* @return \Zend\Http\Headers
*/
public function getHeaders()
{
$headers = parent::getHeaders();
if (!$headers->has('content-type')) {
$headers->addHeaderLine('content-type', 'application/problem+json');
}
return $headers;
}
/**
* Override reason phrase handling
*
* If no corresponding reason phrase is available for the current status
* code, return "Unknown Error".
*
* @return string
*/
public function getReasonPhrase()
{
if (! empty($this->reasonPhrase)) {
return $this->reasonPhrase;
}
if (isset($this->recommendedReasonPhrases[$this->statusCode])) {
return $this->recommendedReasonPhrases[$this->statusCode];
}
return 'Unknown Error';
}
}
在我的控制器内部,我使用了:
return new ApiProblemResponse(
new ApiProblem(ApiProblemResponse::STATUS_CODE_501, 'Example of JSON_PRETTY_PRINT response.')
);
并做到了:
{
"type": "http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec10.html",
"title": "Not Implemented",
"status": 501,
"detail": "Example of JSON_PRETTY_PRINT response."
}