gpt4 book ai didi

json - JMS 将 ArrayCollection 序列化为对象

转载 作者:行者123 更新时间:2023-12-04 15:10:09 27 4
gpt4 key购买 nike

我正在使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com