使用 JMS 序列化程序仅将实体关系序列化为 Id [英] Serializing Entity Relation only to Id with JMS Serializer
问题描述
我正在尝试使用 JMS Serializer 序列化实体关系.
I'm trying to serialize a entity relation with JMS Serializer.
这是实体:
class Ad
{
/**
* @Type("string")
* @Groups({"manage"})
*
* @var string
*/
private $description;
/**
* @Type("Acme\SearchBundle\Entity\Country")
* @Groups({"manage"})
*
* @var \Acme\SearchBundle\Entity\Country
*/
private $country;
/**
* @Type("string")
* @Groups({"manage"})
*
* @var string
*/
private $title;
/**
* Set description
*
* @param string $description
* @return Ad
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set country
*
* @param \Acme\SearchBundle\Entity\Country $country
* @return Ad
*/
public function setCountry($country)
{
$this->country= $country;
return $this;
}
/**
* Get country
*
* @return string
*/
public function getCountry()
{
return $this->country;
}
/**
* Set title
*
* @param string $title
* @return Ad
*/
public function setTituloanuncio($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
}
以及关系的实体:
class Country
{
/**
* @Type("string")
* @Groups("manage")
*
* @var string
*/
private $id;
/**
* @Type("string")
* @Groups("admin")
*
* @var string
*/
private $description;
/**
* Set description
* @Groups("")
*
* @param string $description
* @return Country
*/
public function setDescripcionpais($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
}
/**
* Get id
*
* @return string
*/
public function getId()
{
return $this->id;
}
}
我序列化了实体,但我不知道如何将国家/地区属性转换为简单字段.
I serialize the entity but I don't know how to convert the country attribute into a simple field.
我在 json 中得到这个结果:
I get this result in json:
{"description":"foo", "title":"bar", "country":{"id":"en"} }
但是我想像这样获取国家/地区的 id 字段:
But I want to get the id field of the country like this:
{"description":"foo", "title":"bar", "country": "en" }
可以使用 JMS 序列化程序吗?
It is possible with JMS Serializer?
谢谢.
@VirtualProperty 不起作用.
@VirtualProperty doesn't work.
推荐答案
是的,你可以使用@VirtualProperty
注解:
Yes, you could use @VirtualProperty
annotation:
/**
* @VirtualProperty
* @SerializedName("foo")
*/
public function bar()
{
return $this->country->getCode();
}
但要注意反序列化:
@VirtualProperty 这个注解可以定义在一个方法上指示该方法返回的数据应显示为对象的属性.
@VirtualProperty This annotation can be defined on a method to indicate that the data returned by the method should appear like a property of the object.
> 注意:这只适用于序列化,完全被忽略在反序列化期间.
希望这有帮助...
这篇关于使用 JMS 序列化程序仅将实体关系序列化为 Id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!