假设我有一个具有“名称”和“密码”属性的 User 类,以及一个“保存”方法。当通过 json_encode 将此类的对象序列化为 JSON 时,该方法被正确跳过,最终得到类似 {'name': 'testName', 'password': 'testPassword'} 的结果。
然而,当通过 json_decode 反序列化时,我最终得到一个 StdClass 对象而不是 User 对象,这是有道理的,但这意味着该对象缺少“保存”方法。有什么方法可以将生成的对象转换为用户,或者向 json_decode 提供一些关于我期望的对象类型的提示?
老问题,但也许有人会发现这很有用。
我创建了一个带有静态函数的抽象类,您可以在对象上继承该函数,以便将任何 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);
您可以使用::DeserializeArray
方法(如果您的 JSON 包含目标对象的数组)。
Here http://ideone.com/1xMSev是一个可运行的示例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)