pyther/json

在json字符串和数据模型之间进行轻量级(反)序列化的工具。

v0.2.2 2024-08-20 09:15 UTC

This package is auto-updated.

Last update: 2024-09-20 09:33:58 UTC


README

pyther/json是一个轻量级(反)序列化工具,在json字符串和数据模型之间转换,具有以下功能:

  • 支持嵌套数组和对象
  • 预定义或自定义命名策略
  • 支持基本或后端枚举。
  • 支持元/属性:
    • 属性重命名
    • 属性排除
    • (数组)数据类型
    • 日期时间格式
    • 枚举格式
  • 以下几种设置:
    • 包含受保护属性
    • 跳过null值
    • 跳过空数组
    • 跳过继承属性
    • 枚举格式(名称,值或完整)
    • 等等...
  • 考虑文档"@var"提示
  • 无外部依赖
  • 易于使用

需求

  • PHP 8.1+

示例

反序列化

    // creates a new order class and populate its properties from a json string or array. 
    $order = Json::deserialize($json, Order::class);

序列化

    // creates a json string populate from orders properties.
    $json = Json::serialize($order);

元/属性

Json

该属性允许手动将单个属性与json属性匹配。该属性将忽略选定的命名策略。

use Pyther\Json\Attributes\Json;

class MyClass
{
    // fill the "sku" from the json "id" property.    
    #[Json("id)]
    public string $sku;
}

JsonIgnore

允许在序列化、反序列化或两者之间忽略单个属性。

use Pyther\Json\Attributes\JsonIgnore;

class MyClass
{
    // ignore on serialization and deserialization
    #[JsonIgnore]
    public string $ignoreMe;

    // ignore on serialization only
    #[JsonIgnore(true, false)]
    public string $ignoreMe;

    // ignore on deserialization only
    #[JsonIgnore(false, true)]
    public string $ignoreMe;
}

JsonType

为单个属性定义数据类型。这对于数组尤其有用,因为PHP中数组缺少类型提示支持。

use Pyther\Json\Attributes\JsonType;

class MyClass
{
    // definfes the type of the array items.
    #[JsonType(OrderItem::class)]
    public array $typedArrayByMeta;

    // possible to replace the missing build in datatype.
    #[JsonType(\int::class)]
    public $intByMeta;
}

JsonDateTime

允许为单个属性定义日期时间格式。

use Pyther\Json\Attributes\JsonDateTime;

class MyClass
{
    // parse this property by the given format.
    #[JsonDateTime("d/m/Y")]
    public string $dayOfBirth;
}

JsonEnum

允许为单个属性定义枚举序列化格式。

use Pyther\Json\Attributes\JsonEnum;

class MyClass
{
    // parse this property by the given format.
    #[JsonEnum(EnumFormat::Name)]
    public Status $status;
}