Home > Enterprise >  symfony deserialize into object with different keys
symfony deserialize into object with different keys

Time:07-07

From an API I get a output like that:

{
  "labelType": "string",
  "labelCode": "string",
  "addInfo2": "",
  "addInfo3": "23536723462",
  "addInfo4": null,
  "addInfo5": null,
  "arrow": "none",
  "articleIdList": [
    "2357789234"
  ],
  "templateName": null,
  "rotationDegrees": "0"
}

Now I want to deserialize this jsonstring into an Object by calling:

$this->serializer->deserialize($jsonLabelMappings, LabelMappings::class, 'json');

But I want that the Object has other keys/attributenames. My object should look like that:

{
  "labelType": "string",
  "labelCode": "string",
  "originCountry": "", /* this is the addInfo2 */
  "gtin": "23536723462", /* this is the ddInfo3 */
  "wildfang": null, /* this is the addInfo4 */
  "arrow": "none",
  "product_ids": [ /* this is the articleIdList */
    "2357789234"
  ],
  "templateName": null,
  "rotationDegrees": "0"
}

Is there any anotation like @Serializer\DeserializeName or something? Or how can I tell my code that the keyName from the json is something other?

CodePudding user response:

Because I didn't get any answer which woul solve my problem with annotations or something "short". I now did it with @Fly_Moe answer:

Should be easy to do by turning the json into an array. Loop through the array and replace the key with the new one. That's what I would do

  • Related