老问题,但也许有人会发现这很有用。
我创建了一个带有静态函数的抽象类,您可以在对象上继承该函数,以便将任何 JSON 反序列化为继承类实例。
abstract class JsonDeserializer
{
    /**
     * @param string|array $json
     * @return $this
     */
    public static function Deserialize($json)
    {
        $className = get_called_class();
        $classInstance = new $className();
        if (is_string($json))
            $json = json_decode($json);
        foreach ($json as $key => $value) {
            if (!property_exists($classInstance, $key)) continue;
            $classInstance->{$key} = $value;
        }
        return $classInstance;
    }
    /**
     * @param string $json
     * @return $this[]
     */
    public static function DeserializeArray($json)
    {
        $json = json_decode($json);
        $items = [];
        foreach ($json as $item)
            $items[] = self::Deserialize($item);
        return $items;
    }
}
您可以通过在具有JSON将具有的值的类上继承它来使用它:
class MyObject extends JsonDeserializer
{
    /** @var string */
    public $property1;
    /** @var string */
    public $property2;
    /** @var string */
    public $property3;
    /** @var array */
    public $array1;
}
用法示例:
$objectInstance = new MyObject();
$objectInstance->property1 = 'Value 1';
$objectInstance->property2 = 'Value 2';
$objectInstance->property3 = 'Value 3';
$objectInstance->array1 = ['Key 1' => 'Value 1', 'Key 2' => 'Value 2'];
$jsonSerialized = json_encode($objectInstance);
$deserializedInstance = MyObject::Deserialize($jsonSerialized);
如果 JSON 包含目标对象的数组,则可以使用该方法。::DeserializeArray
下面是一个可运行的示例。