我有一个实体产品,与实体属性具有一对多关系。当我使用 JMS 序列化程序序列化产品实例时,我得到以下 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"
}]
}
我尝试让序列化程序将属性集合序列化为将某个字段用作键的对象。例如,名称字段。所需的输出为:
{
"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>
然后,我将 getKeyedProperties
方法添加到 Foo'BarBundle'Document'Article
中的文档类中:
/**
* 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;
}
现在,序列化输出包含一个对象属性,这些属性是按名称键控的序列化文章属性。