问题
Acme\StoreBundle\Document\Person
/**
* @MongoDB\Document
*/
class Person
{
/**
* @MongoDB\bool
*/
private $hasemail;
/**
* @MongoDB\EmbedOne(targetDocument="Gps")
*/
private $gps;
/**
* @MongoDB\Field(name="email", type="collection")
*/
private $email;
}
...
Acme\StoreBundle\Document\Gps
/**
* @MongoDB\EmbeddedDocument
*/
class Gps
{
/**
* @MongoDB\Field(type="float")
*/
private $latitude;
/**
* @MongoDB\Field(type="float")
*/
private $longitude;
}
...
mongo json document
{
"hasemail": true,
"gps": {
"latitude": 42.941579990394,
"longitude": -85.244641161525
},
"email": [
"sdfgsdfg@sfgsdfg.org",
"sdfgsdfg@fgsdfg.com",
"sdfgsdfg@sdfgsdfg.com"
]
}
serializing mongo document to json works perfect. but deserializing json to document throws an error: "Expected argument of type 'Acme\StoreBundle\Document\Gps', 'array' given"
deserialize code:
$post = $request->getContent();
$serializer = $this->get('serializer');
$person = $serializer->deserialize($post, Person::class, 'json');
回答1:
so finally I used ReflectionExtractor and it worked like charm. No custom denormalizers necessary.
http://symfony.com/doc/current/components/serializer.html#recursive-denormalization-and-type-safety
$post = $request->getContent();
$normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor()); //
$serializer = new Serializer(array($normalizer, new DateTimeNormalizer(\DateTime::ISO8601), new ObjectNormalizer()), [new JsonEncoder()]);
$person = $serializer->deserialize($post, Person::class, 'json');
$dm = $this->get('doctrine_mongodb')->getManager();
$dm->persist($person);
$dm->flush();
return new Response('Created id ' . $person->getId());
回答2:
Your $post
is likely an array and not a raw JSON object as you're expecting.
[{
key: value
}]
is different from..
{
key: value
}
Separately, there looks to be a separate issue based on your error message and the example code you have here.
Acme\StoreBundle\Document\Gps
is the expected class, while deserializing Voter::class
so you may want to check your namespaces and class names as well.
来源:https://stackoverflow.com/questions/44444807/deserializing-json-to-embedded-object-in-symfony-3-2-expected-argument-of-type