mihasicehcek/json_parser

简单的json_decode/json_encode PHP函数包装器。在解码/编码失败时抛出异常

v1.0.2 2017-03-17 12:25 UTC

This package is auto-updated.

Last update: 2024-09-29 04:42:37 UTC


README

Latest Stable Version Total Downloads License

安装

使用Composer

$ composer require mihasicehcek/json_parser

简单示例

简单的json_decode/json_encode PHP函数包装器。在解码/编码失败时抛出异常。

try{
  $json = '{"integer":1';
  $result = \JsonParser\JsonParser::jsonDecode('{"integer":1');
}catch(\JsonParser\Exception $ex){
  print_r("Message: ".$ex->getMessage().", code: ".$ex->getCode()); //Message: Syntax error, code: 4
}

try{
  $a = new stdClass();
  $b = new stdClass();
  $a->b = $b;
  $b->a = $a;
  $result = \JsonParser\JsonParser::jsonEncode($a);
}catch(\JsonParser\Exception $ex){
  print_r("Message: ".$ex->getMessage().", code: ".$ex->getCode()); //Message: The object or array passed to json_encode include recursive references and cannot be encoded, code: 7
}

库有两个公共方法 \JsonParser\JsonParser::jsonDecode() 用于序列化和 \JsonParser\JsonParser::jsonEncode() 用于反序列化。这些方法的签名与 json_decodejson_encode 相同。但与原生函数不同,库在解码/编码出错时抛出异常。每个解码/序列化错误都有异常。错误列表的完整信息请参阅 json_last_error

异常

库检测并抛出以下异常

  • \JsonParser\SyntaxException - 语法错误。
  • \JsonParser\ControlCharacterException - 控制字符错误,可能编码错误。
  • \JsonParser\DepthException - 超过最大堆栈深度。
  • \JsonParser\InfOrNanException - json_encode() 传入的值包含 NAN 或 INF。
  • \JsonParser\InvalidPropertyNameException - 在将 JSON 对象解码为 PHP 对象时,json_decode() 传入的字符串中包含以 \u0000 字符开头的键。
  • \JsonParser\RecursionException - json_encode() 传入的对象或数组包含递归引用,无法编码。
  • \JsonParser\StateMismatchException - 状态不匹配(无效或格式不正确的 JSON)。
  • \JsonParser\UnsupportedTypeException - 给 json_encode() 提供了不支持的数据类型,例如资源。
  • \JsonParser\Utf8Exception - UTF-8 字符格式错误,可能编码错误。
  • \JsonParser\Utf16Exception - 在 json_encode() 传入的 JSON 字符串中包含单对 UTF-16 代理。

所有这些异常都扩展了基类 \JsonParser\Exception