ksmz/json

此包已废弃,不再维护。未建议替代包。

带有可捕获异常的JSON编码/解码包装器

v0.1 2018-06-14 08:02 UTC

This package is auto-updated.

Last update: 2022-06-20 19:17:03 UTC


README

Build Status Coveralls StyleCI

带有特定、可捕获异常的json_encode/decode包装器。

安装

composer require ksmz/json

基本用法

use ksmz\json\Json;

Json::encode(['foo' => 'bar']);

异常

所有异常都继承自 ksmz\json\Exceptions\JsonException

try {
    Json::encode(...);
} catch (RecursionException $exception) {
    // Specific exception
} catch (JsonException $exception) {
    // All possible exceptions
}

可以通过相应的异常获取错误代码和消息($e->getMessage()/$e->getCode())。代码对应于各自的错误 常量

对于消息,异常与 json_last_error_msg() 可能返回的消息相同。请查看 php-src 中的示例。

可用的异常

public static $errors = [
    JSON_ERROR_DEPTH                 => DepthException::class,
    JSON_ERROR_STATE_MISMATCH        => InvalidJsonException::class,
    JSON_ERROR_CTRL_CHAR             => ControlCharacterException::class,
    JSON_ERROR_SYNTAX                => SyntaxException::class,
    JSON_ERROR_UTF8                  => Utf8Exception::class,
    JSON_ERROR_UTF16                 => Utf16Exception::class,
    JSON_ERROR_RECURSION             => RecursionException::class,
    JSON_ERROR_INF_OR_NAN            => InfOrNanException::class,
    JSON_ERROR_UNSUPPORTED_TYPE      => UnsupportedTypeException::class,
    JSON_ERROR_INVALID_PROPERTY_NAME => InvalidPropertyNameException::class,
];

一些异常是自解释的,而一些则稍微模糊。请查看 tests 中的示例。所有异常测试都使用与PHP内部测试ext-json相同的“输入”。