1

エンティティPropertyと一対多の関係を持つエンティティProductがあります。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 に答える