Raf*_*809 6 serialization json symfony jmsserializerbundle
我正在使用JMS Serializer.当它与Doctrine ArrayCollection类型一起使用时,JsonSerializer给出了一个不正确的数组格式.指定的结果应遵循格式,[ {}, {} ]但它给了我{ 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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我直接序列化用户实体,则不会发生这种情况:
{
"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
}
]
}
Run Code Online (Sandbox Code Playgroud)
任何线索?
您需要重置 ArrayCollection 数组中的键:
$associative = new ArrayCollection([0 => 1, 2 => 1]);
$list = new ArrayCollection($associative->getValues());
Run Code Online (Sandbox Code Playgroud)
正如 github 上的 @stof Sad 所说:
如果您的数组未使用从 0 到 count($array) - 1 的序列进行索引,则预期行为是获取 JS 对象而不是数组,因为这就是关联数组需要转换为 JSON 的方式。如果键不是这样的序列,则您的数组是一个映射,而不是一个列表。
看一下例子:
php > echo json_encode([0 => 1, 1 => 1]);
[1,1]
php > echo json_encode([0 => 1, 2 => 1]);
{"0":1,"2":1}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2681 次 |
| 最近记录: |