Php 使用JsonModel作为对象返回空数组

Php 使用JsonModel作为对象返回空数组,php,json,zend-framework2,Php,Json,Zend Framework2,我正在使用Zend Framework 2创建一个REST方法,该方法返回JSON响应。为此,我使用以下代码: return new JsonModel($result); 在某些情况下,结果是一个空数组,JsonModel输出为[]。是否可以强制JsonModel将空数组显示为对象,即{} 在PHP中,您可以执行以下操作: echo json_encode(array(), JSON_FORCE_OBJECT); zf2中的JsonModel是否也可以使用类似的JSON\u FORCE\u

我正在使用Zend Framework 2创建一个REST方法,该方法返回JSON响应。为此,我使用以下代码:

return new JsonModel($result);
在某些情况下,结果是一个空数组,JsonModel输出为
[]
。是否可以强制JsonModel将空数组显示为对象,即
{}

在PHP中,您可以执行以下操作:

echo json_encode(array(), JSON_FORCE_OBJECT);
zf2中的JsonModel是否也可以使用类似的
JSON\u FORCE\u OBJECT
选项?我尝试了以下所有组合,但没有运气

return new JsonModel(array(), JSON_FORCE_OBJECT);

如果您遵循了代码,就会发现Zend提供的
JsonModel
是不可能的


Zend\View\Model\JsonModel
具有以下序列化功能:

public function serialize()
{
    $variables = $this->getVariables();
    if ($variables instanceof Traversable) {
        $variables = ArrayUtils::iteratorToArray($variables);
    }

    $options = [
        'prettyPrint' => $this->getOption('prettyPrint'),
    ];

    if (null !== $this->jsonpCallback) {
        return $this->jsonpCallback.'('.Json::encode($variables, false, $options).');';
    }
    return Json::encode($variables, false, $options);
}
private static function encodeViaPhpBuiltIn($valueToEncode, $prettyPrint = false)
{
    if (! function_exists('json_encode') || static::$useBuiltinEncoderDecoder === true) {
        return false;
    }

    $encodeOptions = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP;

    if ($prettyPrint) {
        $encodeOptions |= JSON_PRETTY_PRINT;
    }

    return json_encode($valueToEncode, $encodeOptions);
}
Json::encode
导致
Zend\Json\Json
,以及
encode()
函数

public static function encode($valueToEncode, $cycleCheck = false, array $options = [])
{
    if (is_object($valueToEncode)) {
        if (method_exists($valueToEncode, 'toJson')) {
            return $valueToEncode->toJson();
        }

        if (method_exists($valueToEncode, 'toArray')) {
            return static::encode($valueToEncode->toArray(), $cycleCheck, $options);
        }
    }

    // Pre-process and replace javascript expressions with placeholders
    $javascriptExpressions = new SplQueue();
    if (isset($options['enableJsonExprFinder'])
       && $options['enableJsonExprFinder'] == true
    ) {
        $valueToEncode = static::recursiveJsonExprFinder($valueToEncode, $javascriptExpressions);
    }

    // Encoding
    $prettyPrint = (isset($options['prettyPrint']) && ($options['prettyPrint'] === true));
    $encodedResult = self::encodeValue($valueToEncode, $cycleCheck, $options, $prettyPrint);

    // Post-process to revert back any Zend\Json\Expr instances.
    $encodedResult = self::injectJavascriptExpressions($encodedResult, $javascriptExpressions);

    return $encodedResult;
}
正如您所看到的,编码函数已经为您注释,因此我们需要
self::encodeValue
函数,点击该函数可以得到:

private static function encodeValue($valueToEncode, $cycleCheck, array $options, $prettyPrint)
{
    if (function_exists('json_encode') && static::$useBuiltinEncoderDecoder !== true) {
        return self::encodeViaPhpBuiltIn($valueToEncode, $prettyPrint);
    }

    return self::encodeViaEncoder($valueToEncode, $cycleCheck, $options, $prettyPrint);
}
根据您的问题判断,您有
json\u encode
内置函数可用,因此我们进入
if()
并执行
self::encodeviaphuiltin()
函数:

public function serialize()
{
    $variables = $this->getVariables();
    if ($variables instanceof Traversable) {
        $variables = ArrayUtils::iteratorToArray($variables);
    }

    $options = [
        'prettyPrint' => $this->getOption('prettyPrint'),
    ];

    if (null !== $this->jsonpCallback) {
        return $this->jsonpCallback.'('.Json::encode($variables, false, $options).');';
    }
    return Json::encode($variables, false, $options);
}
private static function encodeViaPhpBuiltIn($valueToEncode, $prettyPrint = false)
{
    if (! function_exists('json_encode') || static::$useBuiltinEncoderDecoder === true) {
        return false;
    }

    $encodeOptions = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP;

    if ($prettyPrint) {
        $encodeOptions |= JSON_PRETTY_PRINT;
    }

    return json_encode($valueToEncode, $encodeOptions);
}
再次进行相同的检查,但最终结果是:

return json_encode($valueToEncode, $encodeOptions);
除了可选的“
JSON\u PRETTY\u PRINT
”选项外,这些选项在函数中设置为硬编码


你想要的答案是:,这是不可能的



但是,从技术上讲,您可以为
JsonModel
编写自己的替换,确保
JsonViewStrategy
使用您自己的模型,然后使用它。。。只是一个选项。

如果您遵循了代码,您会发现使用Zend提供的
JsonModel
是不可能的


Zend\View\Model\JsonModel
具有以下序列化功能:

public function serialize()
{
    $variables = $this->getVariables();
    if ($variables instanceof Traversable) {
        $variables = ArrayUtils::iteratorToArray($variables);
    }

    $options = [
        'prettyPrint' => $this->getOption('prettyPrint'),
    ];

    if (null !== $this->jsonpCallback) {
        return $this->jsonpCallback.'('.Json::encode($variables, false, $options).');';
    }
    return Json::encode($variables, false, $options);
}
private static function encodeViaPhpBuiltIn($valueToEncode, $prettyPrint = false)
{
    if (! function_exists('json_encode') || static::$useBuiltinEncoderDecoder === true) {
        return false;
    }

    $encodeOptions = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP;

    if ($prettyPrint) {
        $encodeOptions |= JSON_PRETTY_PRINT;
    }

    return json_encode($valueToEncode, $encodeOptions);
}
Json::encode
导致
Zend\Json\Json
,以及
encode()
函数

public static function encode($valueToEncode, $cycleCheck = false, array $options = [])
{
    if (is_object($valueToEncode)) {
        if (method_exists($valueToEncode, 'toJson')) {
            return $valueToEncode->toJson();
        }

        if (method_exists($valueToEncode, 'toArray')) {
            return static::encode($valueToEncode->toArray(), $cycleCheck, $options);
        }
    }

    // Pre-process and replace javascript expressions with placeholders
    $javascriptExpressions = new SplQueue();
    if (isset($options['enableJsonExprFinder'])
       && $options['enableJsonExprFinder'] == true
    ) {
        $valueToEncode = static::recursiveJsonExprFinder($valueToEncode, $javascriptExpressions);
    }

    // Encoding
    $prettyPrint = (isset($options['prettyPrint']) && ($options['prettyPrint'] === true));
    $encodedResult = self::encodeValue($valueToEncode, $cycleCheck, $options, $prettyPrint);

    // Post-process to revert back any Zend\Json\Expr instances.
    $encodedResult = self::injectJavascriptExpressions($encodedResult, $javascriptExpressions);

    return $encodedResult;
}
正如您所看到的,编码函数已经为您注释,因此我们需要
self::encodeValue
函数,点击该函数可以得到:

private static function encodeValue($valueToEncode, $cycleCheck, array $options, $prettyPrint)
{
    if (function_exists('json_encode') && static::$useBuiltinEncoderDecoder !== true) {
        return self::encodeViaPhpBuiltIn($valueToEncode, $prettyPrint);
    }

    return self::encodeViaEncoder($valueToEncode, $cycleCheck, $options, $prettyPrint);
}
根据您的问题判断,您有
json\u encode
内置函数可用,因此我们进入
if()
并执行
self::encodeviaphuiltin()
函数:

public function serialize()
{
    $variables = $this->getVariables();
    if ($variables instanceof Traversable) {
        $variables = ArrayUtils::iteratorToArray($variables);
    }

    $options = [
        'prettyPrint' => $this->getOption('prettyPrint'),
    ];

    if (null !== $this->jsonpCallback) {
        return $this->jsonpCallback.'('.Json::encode($variables, false, $options).');';
    }
    return Json::encode($variables, false, $options);
}
private static function encodeViaPhpBuiltIn($valueToEncode, $prettyPrint = false)
{
    if (! function_exists('json_encode') || static::$useBuiltinEncoderDecoder === true) {
        return false;
    }

    $encodeOptions = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP;

    if ($prettyPrint) {
        $encodeOptions |= JSON_PRETTY_PRINT;
    }

    return json_encode($valueToEncode, $encodeOptions);
}
再次进行相同的检查,但最终结果是:

return json_encode($valueToEncode, $encodeOptions);
除了可选的“
JSON\u PRETTY\u PRINT
”选项外,这些选项在函数中设置为硬编码


你想要的答案是:,这是不可能的



但是,从技术上讲,您可以为
JsonModel
编写自己的替换,确保
JsonViewStrategy
使用您自己的模型,然后使用它。。。只是一个选项。

使用响应对象:

    $result   = array();
    $data     = json_encode($result, JSON_FORCE_OBJECT);
    $response = $this->getResponse();
    return $response->setContent($data);

使用响应对象:

    $result   = array();
    $data     = json_encode($result, JSON_FORCE_OBJECT);
    $response = $this->getResponse();
    return $response->setContent($data);