PHP json_encode类私有成员

rrr*_*ass 35 php json

我正在尝试JSON编码PHP中的一些对象,但我遇到了一个问题:我想编码由类私有成员保存的数据.我发现这段代码通过调用一个编码函数来编码这个对象:

public function encodeJSON() 
{ 
    foreach ($this as $key => $value) 
    { 
        $json->$key = $value; 
    } 
    return json_encode($json); 
}
Run Code Online (Sandbox Code Playgroud)

但是,这只适用于我想编码的对象内部不包含其他对象的情况.我怎么能不仅编码"外部"对象,还编码任何作为对象的成员?

sam*_*777 72

使用私有属性序列化对象的最佳方法是实现\ JsonSerializable接口,然后实现自己的JsonSerialize方法以返回序列化所需的数据.

<?php

class Item implements \JsonSerializable
{
    private $var;
    private $var1;
    private $var2;

    public function __construct()
    {
        // ...
    }

    public function jsonSerialize()
    {
        $vars = get_object_vars($this);

        return $vars;
    }
}
Run Code Online (Sandbox Code Playgroud)

json_encode 现在将正确序列化您的对象.


luc*_*cas 35

如果你使用的是PHP 5.4,你可以使用JsonSerializable接口:http://www.php.net/manual/en/class.jsonserializable.php

您只需在类中实现一个jsonSerialize方法,该方法返回您想要编码的内容.

然后当你将对象传递给json_encode时,它将编码jsonSerialize的结果.


Ole*_*leg 14

无论如何.您需要在类中创建公共方法以返回json编码的所有字段

public function getJSONEncode() {
    return json_encode(get_object_vars($this));
}
Run Code Online (Sandbox Code Playgroud)


小智 12

我认为@ Petah有最好的方法,但这样你就失去了数组或对象的属性.所以我添加了一个递归执行的函数:

function json_encode_private($object) {

    function extract_props($object) {
        $public = [];

        $reflection = new ReflectionClass(get_class($object));

        foreach ($reflection->getProperties() as $property) {
            $property->setAccessible(true);

            $value = $property->getValue($object);
            $name = $property->getName();

            if(is_array($value)) {
                $public[$name] = [];

                foreach ($value as $item) {
                    if (is_object($item)) {
                        $itemArray = extract_props($item);
                        $public[$name][] = $itemArray;
                    } else {
                        $public[$name][] = $item;
                    }
                }
            } else if(is_object($value)) {
                $public[$name] = extract_props($value);
            } else $public[$name] = $value;
        }

        return $public;
    }

    return json_encode(extract_props($object));
}
Run Code Online (Sandbox Code Playgroud)

编辑:在数组循环内添加了is_object()检查,以避免在数组元素不是对象(如字符串或数字)时在下一个extract_props()调用中出现get_class()异常.


Jon*_*han 6

我认为这可能是使用 Traits 的一个很好的例子

使用下面的代码,我在应用程序的多个点实现了jsonSerialized 接口,同时保持代码的可管理性

https://gist.github.com/zburgermeiszter/7dc5e65b06bb34a325a0363726fd8e14

trait JsonSerializeTrait
{
    function jsonSerialize()
    {
        $reflect = new \ReflectionClass($this);
        $props   = $reflect->getProperties(\ReflectionProperty::IS_STATIC | \ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED | \ReflectionProperty::IS_PRIVATE);

        $propsIterator = function() use ($props) {
            foreach ($props as $prop) {
                yield $prop->getName() => $this->{$prop->getName()};
            }
        };

        return iterator_to_array($propsIterator());
    }
}
Run Code Online (Sandbox Code Playgroud)

那么你只需要做

class YourClass implements JsonSerializable 
{
    use JsonSerializeTrait;

    ... normal encapsulated code...
}
Run Code Online (Sandbox Code Playgroud)