JMS序列化器反序列化嵌套对象

时间:2019-03-04 10:17:36

标签: php json symfony serialization

我正在使用:https://jmsyst.com/libs/serializer

用于反序列化json对象。 目前我有这个:

/**
 * @param int $id
 * @return Customer
 * @throws \Http\Client\Exception
 */
public function get(int $id): Customer
{
    $response = $this->client->get('/customers/' . $id);

    $data = json_encode(json_decode(
        $response->getBody()->getContents()
    )->data->attributes);

    return $this
        ->serializer
        ->deserialize($data, Customer::class, 'json');
}

我在这里收到的json看起来像这样:

   {
    "data": {
            "type": "customer",
            "id": "4356456",
            "links": {
                    "self":"https:\/\/api.ecurring.com\/customers\/345656"
            },
            "attributes": {
                    "gender": "m",
            "first_name": "Laurens"
        }
    }

是否可以告诉JMS它应该自动从data->attributes开始,而不是像这样做一些肮脏的事情:

 $data = json_encode(json_decode(
            $response->getBody()->getContents()
        )->data->attributes);

1 个答案:

答案 0 :(得分:0)

您可以检查排除政策。

阅读文档,真的很有帮助。

Exclusion policyAnnotation