Symfony 2 / Php : json_encode

≯℡__Kan透↙ 提交于 2021-01-29 02:58:42

问题


I've been looking to a solution to my problem for a while without success so I'm asking here.

How can we return a json-encoded result on an array of objects (or just an object) containing private properties ?

Indeed, when you use json_encode($myObject), it won't display the private or protected properties, which are present everywhere in the model when using Symfony...

I'm surprised I couldn't find any method like json_encode that would call getters instead of properties themselves.

Any idea ?

EDIT

In that case I would rather do a unique function that looks like :

public function toArray() {
    $vars = get_object_vars($this);
    $result = array();
    foreach ($vars as $key => $value) {
        if (is_object($value)) {
            $result[$key] = toArray($value);
        } else {
            $result[$key] = $value;
        }
    }
    return $result;
}

in order to avoid rewriting every property name everytime...

But anyway I think I'll just create an array containing the vars I need, so that I won't touch the model (which is generated code).


回答1:


Right now there is no way for this. Only php serialize/unserialize handles the true serialisation of objects.

You'll have to implement them yourselve, or rather let objects return their json values themselves.

You will have to implement your own method toArray() where you expose all your private values in an array:

public function toArray()
{
  return array(
      'property1' => $this->myproperty1,
      'property2' => $this->myproperty2
  );
}

And call it like this:

json_encode(MyObject->toArray());

[Edit: this question is not about doctrine, but since you mention both symfony2 and the model, you can consider using Array Hydration for your model: http://www.doctrine-project.org/docs/orm/2.0/en/reference/dql-doctrine-query-language.html#array-hydration ]




回答2:


Have you try GetSetMethodNormalizer ? http://api.symfony.com/2.0/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.html Ex. https://stackoverflow.com/a/6709828/520114



来源:https://stackoverflow.com/questions/8387162/symfony-2-php-json-encode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!