mobijay/json-serializer

使用属性定义序列化 PHP 对象

0.2.5 2024-03-28 13:44 UTC

This package is auto-updated.

Last update: 2024-09-28 15:12:41 UTC


README

您要序列化的类必须 实现 \JsonSerializable

然后您需要 使用 JsonSerializeByAttribute 特性。它包含序列化方法;

对于您想要序列化的每个字段或方法,添加以下属性 `#[JsonSerialize]`,字段名将用作序列化 JSON 中的键。

如果您想要更改 JSON 中的键,必须添加 `#[JsonSerialize('customPrivateField')]`

如果您不想序列化 null 值,必须指定它 `#[JsonSerialize('customPrivateField',false)]`,默认为 true

一个完整的示例

`

{
use JsonSerializeByAttribute;

    #[JsonSerialize('nullField1',false)]
    private ?string $nullField1;
    #[JsonSerialize('nullField2',true)]
    private ?string $nullField2 = null;
    
    #[JsonSerialize('customPrivateField')]
    private $privateField;

    public $disturbanceField1;
    private $disturbanceField2;

    #[JsonSerialize] 
    public $publicField;

    #[JsonSerialize] public Carbon $carbonField;
    #[JsonSerialize] public array $unSetArrayField;
    #[JsonSerialize] public array $arrayField;
    #[JsonSerialize] public array $associativeArrayField;

    public JsonTestOneNested $jsonTestOneNested1;

    #[JsonSerialize]
    public JsonTestOneNested $jsonTestOneNested2;

    #[JsonSerialize("objectWithoutSerializable")]
    public JsonTestOneNestedWithoutJsonSerializable $jsonTestOneNestedWithoutJsonSerializable1;

    public function __construct()
    {
        $this->privateField = 'privateFieldValue';
        $this->publicField = 'publicFieldValue';
        $this->carbonField = Carbon::createFromFormat('Y-m-d H:i:s', '2023-10-23 11:33:32');
        $this->associativeArrayField = ["testKey1" => "testValue1", "testKey2" => "testValue2",];
        $this->arrayField = ["test1", "test2"];
        $this->jsonTestOneNested2 = new JsonTestOneNested();
        $this->jsonTestOneNestedWithoutJsonSerializable1 = new JsonTestOneNestedWithoutJsonSerializable();

    }


    #[\Mobijay\JsonSerializer\Attributes\JsonSerialize('customPublicMethod')]
    public function publicMethod()
    {
        return 'publicMethodValue';
    }

    #[\Mobijay\JsonSerializer\Attributes\JsonSerialize]
    public function privateMethod()
    {
        return 'privateMethodValue';
    }

    public function disturbanceMethod()
    {
        return 'disturbanceMethodValue';
    }

}

class JsonTestOneNested implements \JsonSerializable
{
use JsonSerializeByAttribute;

    #[JsonSerialize('nestedCustomPrivateField')]
    private $privateField = "nestedPrivateFieldValue";

}

class JsonTestOneNestedWithoutJsonSerializable
{
private $privateField = "nestedPrivateFieldValueWithout";
public $publicFieldWithoutSerializable = "publicFieldWithoutSerializableValue";
}```