如何在Symfony中配置JMSSerializer来将自定义类序列化到int或从int序列化



我正在开发一个基于Symfony 3.4的web应用程序项目,该项目使用JMSSerializer将不同的自定义类序列化为JSON,以将这些数据发送到移动应用程序。

如何将自定义类序列化/反序列化为int


假设我们有以下类:

<?php
// AppBundle/Entity/...
class NotificationInfo {
public $date;      // DateTime
public $priority;  // Int 1-10
public $repeates;  // Boolean
public function toInt() {
// Create a simple Int value
//  date = 04/27/2020
//  priority = 5
//  repeats = true
//  ==> int value = 4272020 5 1 = 427202051
}
public function __construnct($intValue) {
// ==> Split int value into date, priority and repeats...
}
}

class ToDoItem {
public $title;
public $tags;
public $notificationInfo;
}

// AppBundle/Resources/config/serializer/Entiy.ToDoItem.yml
AppBundleEntityToDoItem:
exclusion_policy: ALL
properties:
title:
type: string
expose: true
tags:
type: string
expose: true
notificationInfo:
type: integer
expose: true

所以类NotificationInfo也有从int创建它并将它序列化到in的功能。如何告诉序列化程序它应该将$notificationInfo的值序列化到int?

我可以使用以下内容:

notificationInfo:
type: AppBundleEntityNotificationInfo
expose: true

然而,在这种情况下,我需要配置NotificationInfo的序列化,在那里我只能指定哪个属性应该序列化到哪个值。。。


编辑:

这是我想要创建的JSON:

{
"title": "Something ToDO",
"tags": "some,tags",
"notificationInfo": 427202051
}

这是我不想找的:

{
"title": "Something ToDO",
"tags": "some,tags",
"notificationInfo": {
"intValue": 427202051
}
}

经过更多的挖掘,我找到了以下解决问题的方法:我添加了一个自定义序列化Handler,它告诉JMSSerializer如何处理我的自定义类:

class NotificationInfoHandler implements SubscribingHandlerInterface {
public static function getSubscribingMethods() {
return [
[
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'json',
'type' => 'NotificationInfo',
'method' => 'serializeNotificationInfoToJson',
],
[
'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
'format' => 'json',
'type' => 'NotificationInfo',
'method' => 'deserializeNotificationInfoToJson',
],
;

public function serializeNotificationInfoToJson(JsonSerializationVisitor $visitor, NotificationInfo $info, array $type, Context $context) {
return $info->toInt();
}
public function deserializeNotificationInfoToJson(JsonDeserializationVisitor $visitor, $infoAsInt, array $type, Context $context) {
return (is_int($infoAsInt) ? NotificationInfo::fromInt($infoAsInt) : NotificationInfo::emptyInfo());
}
}

由于autowire,处理程序被自动添加,并且可以在序列化程序元数据中使用:

notificationInfo:
type: NotificationInfo
expose: true

您可以使用VirtualProperty方法添加您类的任何方法转换为json响应

use JMSSerializerAnnotation as Serializer;
class NotificationInfo 
{
/**
* @return int
* @SerializerVirtualProperty()
* @SerializerSerializedName("formatedLocation")
*/
public function toInt()
{
return 4272020;
}
}

最新更新