【发布时间】:2020-04-27 15:15:51
【问题描述】:
我正在开发一个基于 Symfony 3.4 的网络应用程序项目,该项目使用 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
AppBundle\Entity\ToDoItem:
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: AppBundle\Entity\NotificationInfo
expose: true
但是在这种情况下,我需要配置NotificationInfo 的序列化,我只能指定哪个属性应该序列化为哪个值...
编辑:
这是我要创建的 JSON:
{
"title": "Something ToDO",
"tags": "some,tags",
"notificationInfo": 427202051
}
这不是我要找的:
{
"title": "Something ToDO",
"tags": "some,tags",
"notificationInfo": {
"intValue": 427202051
}
}
【问题讨论】:
-
你试过JMS序列化器的VirtualProperty()方法吗?