1

我有一个实体Product与实体Property具有一对多关系。当我使用 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"
        }
    }
}

实现这一目标的最佳方法是什么?

4

1 回答 1

1

好的,我想通了:

首先在序列化映射中添加一个虚拟属性并排除原始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;
}

现在,序列化输出包含一个对象属性,这些属性是按名称键入的序列化文章属性。

于 2015-01-21T09:09:44.290 回答