json - JMS 将 ArrayCollection 序列化为对象

标签 json symfony serialization jmsserializerbundle

我正在使用 JMS 序列化程序。当 JsonSerializer 与 Doctrine ArrayCollection 类型一起工作时,它给了我不正确的数组格式。指定的结果应遵循格式 [ {}, {} ]但它给了我 { 1: {}, 2: {} } .

有关此方案的其他信息。它仅在我尝试序列化包含包含 ArrayCollection 的对象且 ArrayCollection 包含第一级对象的对象时发生。例如:

{  
   "description":"Text provided",
   "date":"1434145921000",
   "oid":1,
   "userCreator":{  
      "username":"name123",
      "password":"psw",
      "oid":2,
      "name":"the-name",
      "lastname":"the-lasname",
      "announcements":{  
         "1":{  
            "description":"Clases de inglés",
            "date":"1434745921000",
            "oid":3
         },
         "2":{  
            "description":"Reparar ordenador",
            "date":"1434145921000",
            "oid":5
         }
      }
   }
}

但是,如果我直接序列化用户实体,则不会发生这种情况:
{  
   "username":"user1",
   "password":"123",
   "oid":2,
   "name":"Rafael",
   "lastname":"Jimenez"
   "announcements":[  
      {  
         "description":"Cargar cajas a la guardilla",
         "date":"1434145921000",
         "oid":1
      },
      {  
         "description":"Contar césped y quitar malas hierbas",
         "date":"1434745921000",
         "oid":3
      },
      {  
         "description":"Reparar ordenador",
         "date":"1434145921000",
         "oid":5
      }
   ]
}

有什么线索吗?

最佳答案

您需要重置 ArrayCollection 数组中的键:

$associative = new ArrayCollection([0 => 1, 2 => 1]);
$list = new ArrayCollection($associative->getValues());

正如@stof 在 github 上悲伤的那样:

If your array is not indexed with a sequence from 0 to count($array) - 1, getting an JS object rather than an array is the expected behaviour, because this is how associative arrays need to be converted to JSON. And if keys are not such sequence, your array is a map, not a list.



看看例子:
php > echo json_encode([0 => 1, 1 => 1]);
[1,1]
php > echo json_encode([0 => 1, 2 => 1]);
{"0":1,"2":1}

关于json - JMS 将 ArrayCollection 序列化为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30821680/

相关文章:

security - Symfony2 每主机访问控制

javascript - 如何将 JSO 转换为 JSON?

javascript - 下拉组件填充数据,只有虚拟数据有效

python - 如何在 Django 中序列化 ImageField?

java - 如何在没有POJO的情况下解析JSON

symfony - Twig:阻止解析客户端模板

php - Symfony 一对多不链接父级

c# - 如何在单元测试中验证序列化的 JSON 在 Python/C# 中是否正确?

c# - 当 xml 有缩进/换行符时,字典的自定义序列化失败

c# - 反序列化错误: value cannot be null. 参数名称:type