强制 JMS 序列化程序输出由特定字段键入的对象
Force JMS Serialiser to output an object keyed by a specific field
我有一个实体 Product 与实体 属性 存在一对多关系。当我使用 JMS Serialiser 序列化产品实例时,我得到以下 JSON 输出:
{
"id": 123,
"name": "Mankini Thong",
"properties": [{
"label": "Minimal size",
"name": "min_size",
"value": "S"
}, {
"label": "Maximum size",
"name": "max_size",
"value": "XXXL"
}, {
"label": "colour",
"name": "Colour",
"value": "Office Green"
}]
}
我尝试让序列化程序将属性集合序列化为一个对象,其中某个字段用作键。例如,name 字段。期望的输出是:
{
"id": 123,
"name": "Mankini Thong",
"properties": {
"min_size": {
"label": "Minimal size",
"value": "S"
},
"max_size": {
"label": "Maximum size",
"value": "XXXL"
},
"colour": {
"label": "Colour",
"value": "Office Green"
}
}
}
实现此目标的最佳方法是什么?
好的,我明白了:
先在序列化映射中增加一个虚拟的属性,排除原来的properties
字段。我的配置在 yaml 中,但使用注释应该没有什么不同:
properties:
properties:
exclude: true
virtual_properties:
getKeyedProperties:
serialized_name: properties
type: array<Foo\BarBundle\Document\Property>
然后我在 Foo\BarBundle\Document\Article
中的文档 class 中添加了 getKeyedProperties
方法:
/**
* Get properties keyed by name
*
* Use the following annotations in case you defined your mapping using
* annotations instead of a Yaml or Xml file:
*
* @Serializer\VirtualProperty
* @Serializer\SerializedName("properties")
*
* @return array
*/
public function getKeyedProperties()
{
$results = [];
foreach ($this->getProperties() as $property) {
$results[$property->getName()] = $property;
}
return $results;
}
现在,序列化输出包含一个对象属性,它是按名称键控的序列化文章属性。
我有一个实体 Product 与实体 属性 存在一对多关系。当我使用 JMS Serialiser 序列化产品实例时,我得到以下 JSON 输出:
{
"id": 123,
"name": "Mankini Thong",
"properties": [{
"label": "Minimal size",
"name": "min_size",
"value": "S"
}, {
"label": "Maximum size",
"name": "max_size",
"value": "XXXL"
}, {
"label": "colour",
"name": "Colour",
"value": "Office Green"
}]
}
我尝试让序列化程序将属性集合序列化为一个对象,其中某个字段用作键。例如,name 字段。期望的输出是:
{
"id": 123,
"name": "Mankini Thong",
"properties": {
"min_size": {
"label": "Minimal size",
"value": "S"
},
"max_size": {
"label": "Maximum size",
"value": "XXXL"
},
"colour": {
"label": "Colour",
"value": "Office Green"
}
}
}
实现此目标的最佳方法是什么?
好的,我明白了:
先在序列化映射中增加一个虚拟的属性,排除原来的properties
字段。我的配置在 yaml 中,但使用注释应该没有什么不同:
properties:
properties:
exclude: true
virtual_properties:
getKeyedProperties:
serialized_name: properties
type: array<Foo\BarBundle\Document\Property>
然后我在 Foo\BarBundle\Document\Article
中的文档 class 中添加了 getKeyedProperties
方法:
/**
* Get properties keyed by name
*
* Use the following annotations in case you defined your mapping using
* annotations instead of a Yaml or Xml file:
*
* @Serializer\VirtualProperty
* @Serializer\SerializedName("properties")
*
* @return array
*/
public function getKeyedProperties()
{
$results = [];
foreach ($this->getProperties() as $property) {
$results[$property->getName()] = $property;
}
return $results;
}
现在,序列化输出包含一个对象属性,它是按名称键控的序列化文章属性。