json - 列表作为 Json 编码返回最后一个索引值
问题描述
在这里,我已将值添加到 contactList.listChild 但字符串列表不会将所有值返回到父列表它只返回最后添加的值。我知道这是一个简单的错误,但我不知道在哪里犯了错误。
任何建议都会有所帮助。
ContactName contactList = new ContactName();
createJson(){
for(int index = 0; index < _contacts.length; index++){
Contact contact = _contacts?.elementAt(index);
List<Item> numbersList = contact.phones.toList();
for(int i = 0; i < numbersList.length; i++ ){
contactList.listChild = [numbersList[i].value];
}
contactList.name = contact.displayName;
lisJson.add(contactList.toJson());
}
var data = {
"data" : lisJson
};
var body = json.encode(data);
print("$body");
}
// here is my model class
class ContactName extends Object {
String name;
List<String> listChild = new List<String>();
Map toJson() => {"name":name, "phone":listChild};
}
这就是我从中得到的
{
"data": [
{
"name": "user1",
"phone": [
"8221551458"
]
},
{
"name": "user2",
"phone": [
"1234567890"
]
}
]
}
// and the output should be something like this
{
"data": [
{
"name": "user1",
"phone": [
"8221551458"
]
},
{
"name": "user2",
"phone": [
"8220780548"
"1234567890"
]
}
]
}
解决方案
你需要更换
contactList.listChild = [numbersList[i].value]
经过
contactList.listChild.add(numbersList[i].value)
您的代码在 for 语句的每次迭代中创建一个新列表,这就是为什么最后一个元素是您看到的唯一元素的原因。
一定要contactList.listChild
在使用它之前进行初始化,否则在尝试添加新元素时会抛出异常。
推荐阅读
- android - 添加多行文本视图的可绘制开头
- python - np.concatenate 错误...ValueError:所有输入数组必须具有相同的维数
- javascript - 如何在 nativescript 中定义默认的 TabView?
- image - 如何使用 jpeg 在压缩图像中找到 jpeg 标头
- python - 如何在 ListView 中包含 CreateView 模板?
- javascript - 如何在 Python 中解析 html 源代码中的 javascript 代码?
- r - 是否有一个 R 函数用于附加具有不相等列的列表
- mysql - Laravel:数据库查询返回标准类而不是数组
- php - Moodle XMLDB 如何将 scema 应用到我的数据库中
- dart - Dart - 通过映射构造函数实例化泛型类型