how can I make JMS/Serializer deserialize this property to object?

744 Views Asked by At

I have the following class

use JMS\Serializer\Annotation as Serializer;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Type;

/**
 * @ExclusionPolicy("none")
 */
class SalesOrderGetResponse
{
    /**
     * @Type("array<Vendor\Module\Model\SalesOrder>")
     * @var SalesOrder[]
     */
    public $mvSalesOrders = [];

    /**
     * @Serializer\Type("Vendor\Module\Model\SalesOrderGetResponseStatus")
     * @var SalesOrderGetResponseStatus
     */
    public $ResponseStatus;

}

And this class

use JMS\Serializer\Annotation as Serializer;

/**
 * @Serializer\ExclusionPolicy("none")
 */
class SalesOrderGetResponseStatus
{
 
    const ERROR_CODE_SUCCESS = 0;

    /**
     * @Serializer\Type("string")
     * @var string
     */
    public $ErrorCode;
}

And I'm trying to use JMS serializer as a standalone library to deserialize the following JSON object into a class.

{
  "mvSalesOrders": [
  ],
  "ResponseStatus": {
    "ErrorCode": "0"
  }
}

Like this

        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
        $encoders = [new JsonEncoder()];
        $normalizers = [new ObjectNormalizer($classMetadataFactory)];

        $serializer = new \Symfony\Component\Serializer\Serializer($normalizers, $encoders);

        $result = new SalesOrderGetResponse();
        $serializer->deserialize($resultJson, SalesOrderGetResponse::class, 'json', [AbstractNormalizer::OBJECT_TO_POPULATE => $result]);

However when I get the deserialized result, the ResponseStatus property is always an array not an instance of the class SalesOrderGetResponseStatus

enter image description here

What am I missing here?

1

There are 1 best solutions below

0
Rafał Długołęcki On

You described deserialization rules for JMS Serializer, but deserializes using Symfony Serializer:

$serializer = new \Symfony\Component\Serializer\Serializer($normalizers, $encoders);

You should do something like that instead:

use JMS\Serializer\SerializerBuilder;

$serializer = SerializerBuilder::create()->build();