提问人:H3lltronik 提问时间:1/23/2023 更新时间:1/23/2023 访问量:149
Symfony 6 系列 |用于反序列化嵌套 JSON 的序列化程序组件
Symfony 6 | Serializer component to deserialize nested JSON
问:
我正在使用 Symfony 的序列化器组件。
https://symfony.com/doc/current/components/serializer.html
我想将以下响应转换为 php 类对象。
{
"data": {
"uuid": "d1830cc0-f35a-11e8-8ca1-5254003b69f1",
"name": "***",
"last_name": "Admin",
"fullname": "***",
"email": "***@***.com",
"created_at": {
"time24": "16:13",
"time": "04:13",
"date": "2018-11-28",
"datetime": "2018-11-28 16:13:22",
"meta": {
"meridiem": "pm",
"day": 28,
"month": 11,
"year": 2018,
"month_name": "November"
}
},
"updated_at": {
"time24": "16:13",
"time": "04:13",
"date": "2018-11-28",
"datetime": "2018-11-28 16:13:22",
"meta": {
"meridiem": "pm",
"day": 28,
"month": 11,
"year": 2018,
"month_name": "November"
}
},
"relationships": {
"role": {
"uuid": "d14ee40e-f35a-11e8-bbfc-5254003b69f1",
"name": "admin",
"label": "Admin",
"public": true,
"created_at": {
"time24": "16:13",
"time": "04:13",
"date": "2018-11-28",
"datetime": "2018-11-28 16:13:21",
"meta": {
"meridiem": "pm",
"day": 28,
"month": 11,
"year": 2018,
"month_name": "November"
}
},
"updated_at": {
"time24": "16:13",
"time": "04:13",
"date": "2018-11-28",
"datetime": "2018-11-28 16:13:21",
"meta": {
"meridiem": "pm",
"day": 28,
"month": 11,
"year": 2018,
"month_name": "November"
}
},
"relationships": {
"permissions": [
{
"name": "admin",
"label": "Admin"
}
]
}
}
}
}
}
我想做的是使用这个网站:
https://jacobdekeizer.github.io/json-to-php-generator/#/
它给了我一长串的类,总而言之,根对象是这样的:
class Response
{
public Data $data;
public function getData(): Data
{
return $this->data;
}
public function setData(Data $data): self
{
$this->data = $data;
return $this;
}
}
然后我尝试像这样反序列化它:
/** @var Response $response */
$response = $this->serializer->deserialize($response->getContent(), Response::class, 'json');
但是我收到以下错误:
Failed to denormalize attribute "data" value for class "App\Http\Booking\Models\Response": Expected argument of type "App\Http\Booking\Models\Data", "array" given at property path "data".
我的序列化对象如下所示:
class MySerializer {
public static function getSerializer()
{
$encoders = [new JsonEncoder()];
$normalizers = [new ObjectNormalizer(), new ArrayDenormalizer()];
return new Serializer($normalizers, $encoders);
}
}
答: 暂无答案
评论