arrays - 列表中的 Dart 对象
问题描述
我是飞镖/颤振的新手。
如何使用列表中的对象?
我有这样的对象:
{
"channelName": "sydneyfunnelaio",
"type": "",
"ChannelPic": "https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
"success": true
}
我怎样才能用它创建列表/数组;
我想喜欢:
[{
"channelName": "sydneyfunnelaio",
"type": "",
"ChannelPic": "https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
"success": true
},{
"channelName": "qweqdqaw",
"type": "",
"ChannelPic": "https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
"success": true
}]
解决方案
你可以尝试这样的事情:
void main() {
List<MyObject> myObjects = [];
myObjects.add(MyObject.fromJson({
"channelName": "sydneyfunnelaio",
"type": "",
"ChannelPic":
"https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
"success": true
}));
myObjects.add(MyObject.fromJson({
"channelName": "qweqdqaw",
"type": "",
"ChannelPic":
"https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
"success": true
}));
print(myObjects);
print(myObjects[0].channelName);
print(myObjects[1].channelName);
myObjects.forEach((obj)=>print(obj.toJson()));
}
class MyObject {
String channelName;
String type;
String channelPic;
bool success;
MyObject({this.channelName, this.type, this.channelPic, this.success});
MyObject.fromJson(Map<String, dynamic> json) {
channelName = json['channelName'];
type = json['type'];
channelPic = json['ChannelPic'];
success = json['success'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['channelName'] = this.channelName;
data['type'] = this.type;
data['ChannelPic'] = this.channelPic;
data['success'] = this.success;
return data;
}
}
推荐阅读
- sql - SQ 写作查询
- postgresql - PostgreSQL 升级到版本 12 - 没有 oid 的更改表太慢
- python - __init__() 应该为使用 boost_python 的 python 模块返回 None,而不是“NoneType”
- r - 将解决方案更改为更有效的解决方案
- python - Python Numpy:int数组可以转换为标量索引
- azure - 当我在应用洞察中打开实时指标时,为什么会出现“不可用:您的应用处于离线状态或使用旧版 SDK”?
- django - Django - 重定向时路径中的重复变量
- swift - ARkit,为什么我不能扩展这个节点?
- microsoft-graph-api - MS 图形用户有多个名为“日历”版本 #2 的日历
- java - 目标是让我的代码打印 5 个数字,然后在另一行打印另外 5 个数字,等等。我似乎做不到。我要补充什么?