我正在使用Symfony Flex 4.1.2,尝试通过JMS序列化程序更新对象实体。
$userService = $this->get('user.service');
$user = $userService->findByOne(array('id' => 1));
$data = [
"spotifyAccessToken" => $accessToken
];
$context = new DeserializationContext();
$context = $context->setAttribute('target', $user);
$content = json_encode($data);
$serializedData = $serializer->deserialize($content, User::class, 'json', $context);
$ user 是 User :: class 的对象,我按$ user,$ context和$ serialized数据的顺序转储,输出在下面
User {#498 ▼
+id: 2
+userName: "spotify:user:1199928833"
+spotifyUserId: "1199928833"
+spotifyAccessToken: "TEST"
+spotifyRefreshToken: "TEST"
+email: "TEST"
+birthday: DateTime @857174400 {#496 ▶}
+image: "TEST"
}
DeserializationContext {#502 ▼
-depth: 0
+attributes: Map {#508 ▼
#elements: array:1 [▼
"target" => User {#498 ▼
+id: 2
+userName: "spotify:user:1199928833"
+spotifyUserId: "1199928833"
+spotifyAccessToken: "TEST"
+spotifyRefreshToken: "TEST"
+email: "TEST"
+birthday: DateTime @857174400 {#496 ▶}
+image: "TEST"
}
]
}
-format: null
-visitor: null
-navigator: null
-metadataFactory: null
-exclusionStrategy: null
-serializeNull: null
-initialized: false
-metadataStack: null
}
User {#536 ▼
+id: null
+userName: null
+spotifyUserId: null
+spotifyAccessToken: "UPDATED_ACCESS_TOKEN"
+spotifyRefreshToken: null
+email: null
+birthday: null
+image: null
}
因此JMS并未对用户对象进行反序列化,我该如何解决?
答案 0 :(得分:0)
在我看来,您是通过
创建一个User
对象
$data = [
"spotifyAccessToken" => $accessToken
];
因此您将收到
+id: null
+userName: null
+spotifyUserId: null
+spotifyAccessToken: "UPDATED_ACCESS_TOKEN"
+spotifyRefreshToken: null
+email: null
+birthday: null
+image: null
那为什么要期待一个完整的User
对象?
现在,如果您需要完整的User
对象并更新了spotifyAccessToken
,我将执行以下操作:
$user->setSpotifyAccessToken($accessToken); // supposing you have a setter for it
$serializedUser = json_encode($user);
$unserializedUser = $serializer->deserialize($serializedUser, User::class, 'json');