polesphp/json

类型安全的面向类的JSON(反)序列化库。

0.1.0 2018-06-26 20:29 UTC

This package is not auto-updated.

Last update: 2024-09-29 05:15:00 UTC


README

poles-json是一个类型安全的面向类的JSON(反)序列化库。

目标

  • 简洁简单的API
  • 对错误严格(总是抛出异常)
  • 默认严格类型检查
  • 通过定义描述输入的纯PHP数据结构来鼓励编写干净代码。

非目标

  • 连接任何PHP Web框架
  • 将JSON属性映射到获取器和设置器方法。我不会做Java Bean的事情。
  • 值验证。这个库将检查你的值是否为字符串,但永远不会验证这个字符串是否至少有n个字符或是否与某个特定的正则表达式匹配。如果你需要这样的验证逻辑,这个库可以很好地与Symfony的验证组件结合使用。

使用方法

首先,定义一个表示你的JSON架构的纯PHP数据结构

<?php

class Person
{
  /** @var int */
  public $id;
  
  /** @var string */
  public $firstname;

  /** @var string */
  public $lastname

  /** @var Address[] */
  public $addresses;
}

class Address
{
  /** int */
  public $civicNo;

  /** string */
  public $street;

  /** string */
  public $city;

  /** string */
  public $country;

  /** string */
  public $postalCode;
}

注意,类型注释是标准的phpDocumentor标签。

一旦你的结构定义得当,你可以轻松地将它转换为JSON,如下所示

<?php

use Poles\Json\ClassSerializer;
use Poles\Json\SerializerConfig;

$subject = <<<JSON
{
  "id": 5,
  "firstname": "John",
  "lastname": "Doe",
  "addresses": [
    {
      "civicNo": 1080,
      "street": "Snowboarding Street",
      "city": "Montreal",
      "country": "Canada",
      "postalCode": "H2K1L3"
    }
  ]
}
JSON;

$serializer = new ClassSerializer(Person::class, new SerializerConfig());

// ----- De-serialization -------
$personInstance = $serializer->deserialize($subject);

// ----- Serialization -----
$originalJson = $serializer->serialize($personInstance);

错误

这个库在错误时抛出异常。反序列化过程中可能出现的错误有

  • Poles\Json\Exceptions\EncodeException:在调用json_encode(序列化)期间发生错误。
  • Poles\Json\Exceptions\DecodeException:在调用json_decode(反序列化)期间发生错误。
  • Poles\Json\Exceptions\TypeMismatchException:JSON值与属性预期的类型或形状不匹配。
  • Poles\Json\Exceptions\UnsupportedTypeException:PHP属性注释了不支持的类型(见以下支持的类型)。
  • Poles\Json\Exceptions\UnresolvableClass:PHP属性注释了类名,但该类不存在。

支持的类型注释

支持的phpDocumentor类型注释有

  • string
  • intinteger
  • float
  • boolboolean
  • array(数组的元素不进行类型检查)
  • null(期望值为null,不期望其他值)
  • 类引用,例如MyClass
  • 类型数组,例如int[]MyClass[](在这种情况下,数组中的每个元素都会递归地检查类型)
  • 复合类型,例如int|string|null

配置

以下是一个序列化器的更复杂配置示例

<?php

use Poles\Json\ClassSerializer;
use Poles\Json\SerializerConfig;

$config = new SerializerConfig();
$config->setCacheDirectory(sys_get_temp_dir()); // Writeable cache directory for production environments
$config->setMaxDepth(200); // Same as the "max depth" argument of json_encode
$config->setOptions(JSON_PRETTY_PRINT); // Same as the "options" argument of json_encode

$serializer = new ClassSerializer(MyClass::class, $config);

未来工作

以下是这个库未来改进的非正式列表

  • 更宽松的“强制”模式,仅在类型无法强制转换为预期类型时抛出。
  • 定义名称重映射逻辑,例如(public $dateOfBirth变为JSON属性date_of_birth
  • 有一个好用的DSL来明确地定义JSON架构,而无需通过反射推断。

许可

此存储库下所有工作均受Apache License 2.0许可。

贡献

如果您想为此项目做出贡献,请确保首先阅读贡献指南