我有一个返回值的方法:
/**
* @ORM\Table()
* @ORM\Entity(repositoryClass="PersonRepository")
*/
class Person {
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
public function getFoo(){
return $this->id + 1;
}
//setters & getters
}
我想包含序列化 Person
对象时 getFoo()
返回的值,使其看起来像这样:
{
'id' : 25
'foo' : 26
}
最佳答案
您需要设置@VirtualProperty
和@SerializedName
。
use JMS\Serializer\Annotation\VirtualProperty;
use JMS\Serializer\Annotation\SerializedName;
class Person {
....
....
....
/**
* @VirtualProperty
* @SerializedName("foo")
*/
public function getFoo(){
return $this->id + 1;
}
....
....
....
}
您可以在这里阅读更多相关信息:http://jmsyst.com/libs/serializer/master/reference/annotations
请注意,这仅适用于序列化,不适用于反序列化。
关于symfony - 在 JMS 中序列化对象时包含方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30816021/