flashport/json-marshaller

一个简单的JSON序列化和反序列化库。

v0.0.12 2024-09-12 09:18 UTC

This package is auto-updated.

Last update: 2024-09-12 09:18:30 UTC


README

此库提供序列化和反序列化功能,允许将JSON字符串转换为对象或反之亦然。

使用方法

对象示例

class Person{

    // It supports custom property names
    #[JsonProperty("fullName")]
    public string $name;
    
    // It also supports validation attributes
    #[JsonValidateRequired]
    public string $email;
    
    // Equals can be a single value or an array
    #[JsonValidateEquals(["active", "inactive"])]
    public string $status;
    
    // It is necessary to define the array type
    #[JsonPropertyType(Address::class)]
    public array $addresses;
    
    // For array with scalar types
    #[JsonPropertyType(ScalarTypes::INTEGER)]
    public array $luckyNumbers;
    
    // The type can be inferred from the property, or from the attribute.
    // At least one is required
    public Address $billingAddress;
    
    #[JsonPropertyType(Address::class)]
    public $shippingAddress;
}

序列化

$json = new \JsonMarshaller\JsonMarshaller();
$jsonString = $json->marshal($myObject);

反序列化

$json = new \JsonMarshaller\JsonMarshaller();
$person = $json->unmarshal($jsonString, Person::class)