从JSON反序列化为PHP,并进行强制转换? [英] Deserializing from JSON into PHP, with casting?

查看:134
本文介绍了从JSON反序列化为PHP,并进行强制转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个具有'name'和'password'属性的User类,以及一个'save'方法.当通过json_encode将此类的对象序列化为JSON时,该方法将被正确跳过,最终得到类似{'name':'testName','password':'testPassword'}之类的东西.

Suppose I have a User class with 'name' and 'password' properties, and a 'save' method. When serializing an object of this class to JSON via json_encode, the method is properly skipped and I end up with something like {'name': 'testName', 'password': 'testPassword'}.

但是,当通过json_decode反序列化时,我最终得到了一个StdClass对象而不是User对象,这很有意义,但这意味着该对象缺少'save'方法.有什么方法可以将生成的对象强制转换为用户,或向json_decode提供一些提示,说明我期望的对象类型是什么?

However, when deserializing via json_decode, I end up with a StdClass object instead of a User object, which makes sense but this means the object lacks the 'save' method. Is there any way to cast the resultant object as a User, or to provide some hint to json_decode as to what type of object I'm expecting?

推荐答案

古老的问题,但也许有人会觉得这很有用.
我创建了一个带有静态函数的抽象类,您可以在对象上继承这些抽象函数,以便将任何JSON反序列化为继承的类实例.

Old question, but maybe someone will find this useful.
I've created an abstract class with static functions that you can inherit on your object in order to deserialize any JSON into the inheriting class instance.

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将具有的值的类上继承它来使用它:

You use it by inheriting it on a class which has the values that your JSON will have:

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方法.

You can use the ::DeserializeArray method if your JSON contains an array of your target object.

此处是可运行的示例.

这篇关于从JSON反序列化为PHP,并进行强制转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆