简体   繁体   中英

Converting JSON to Doctrine Entity in Symfony

I'm currently working on building an API with the Symfony framwork. I've done enough reading to know to use the Serialization component, and built some custom normalizers for my entities. The way it currently works is:

JSON -> Array(Decode) -> User Entity(Denormalize)

This was working find as long as the request content was a JSON representation of the user, example:

{
  "email": "demouser@email.com",
  "plainPassword": "demouser",
  "first_name" : "Demo",
  "last_name" : "User"
}

A user entity is created using the following code in my controller:

    $newuser = $this->get('api.serializer.default')->deserialize($request->getContent(), WebsiteUser::class, 'json');

However, I'd like to nest the user JSON in the 'data' property of a JSON object, which will allow consumers to pass additional metadata with the request, example:

{
  "options": [
    {
      "foo": "bar"
    }
  ],
  "data": [
    {
      "email": "demouser@email.com",
      "plainPassword": "demouser",
      "first_name": "Demo",
      "last_name": "User"
    }
  ]
}

The main issue this causes is that the deserialization does not succeed because the JSON format has changed.

The only solution I've considered so far is to json_decode the whole request body, grab the 'data' element of that array, and pass the contents of the data element to the denormalizer (instead of the deserializer).

Is there a better way to solve this problem?

You should be able to get a specific key of your request body like follows:

$newuser = $this->get('api.serializer.default')->deserialize(
    $request->request->get('data'), WebsiteUser::class, 'json'
);

If you are not able to retrieve the data from key without decoding your request body, look at this bundle , it consists in only one EventListener that replaces the request body after decode it.

You can easily integrate the same logic in your application, or requiring the bundle directly (which works well).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM