Search code examples
phpsymfonydeserializationjson-deserializationjmsserializerbundle

Symfony JMS Serializer deserialize array of jsons to an entitie


I have this string:

[{
    "box": [{
        "UID": "bid1106"
    }, {
        "UID": "bid565"
    }, {
        "UID": "bid1105"
    }]
}, {
    "topseller": [{
        "UID": "pid1816z1"
    }, {
        "UID": "pid8840z100z06"
    }, {
        "UID": "pid2942z01z18"
    }, {
        "UID": "pid5863z0"
    }]
}, {
    "global": {
        "templatename": "homepage",
        "locationid": "",
        "controlgroup": "false"
    }
}]

I need somehow to make Object using JMS serializer.

$obj = $this->serializer->deserialize($jsonData, ObjectClass::class, 'json');

And my ObjectClass.php class looks like this

class ObjectClass
{
    private $box = [];
    private $topseller = [];
    private $global = [];
    ....
}

Any suggestions, how I can make it as a single Object?


Solution

  • I just figure it out by my self:

        $newArray =[];
        foreach (json_decode($jsonData, true) as $item) {
            $key = array_keys($item)[0];
            $newArray[$key] = $item[$key];
        }
    
    
        $obj = $this->serializer->deserialize(json_encode($newArray), ObjectClass::class, 'json');