php 如何使JMS/Serializer将此属性反序列化为对象?

slwdgvem  于 2023-06-04  发布在  PHP
关注(0)|答案(1)|浏览(156)

我有下面的课

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;

}

而这门课

use JMS\Serializer\Annotation as Serializer;

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

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

我尝试使用JMS序列化器作为一个独立的库,将下面的JSON对象反序列化为一个类。

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

就像这样

$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]);

但是,当我获得反序列化结果时,ResponseStatus属性始终是一个数组,而不是类SalesOrderGetResponseStatus的示例

我错过了什么?

7vux5j2d

7vux5j2d1#

您描述了JMS Serializer的反序列化规则,但反序列化使用的是Symfony Serializer:

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

你应该这样做:

use JMS\Serializer\SerializerBuilder;

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

相关问题