json - 解析json数组响应/颤动
问题描述
根据本手册 https://www.bezkoder.com/dart-flutter-parse-json-string-array-to-object-list/ Dart/Flutter 将 JSON 对象数组解析为 List
来自服务器的 JSON
{"myChannels":[{"id":"2","name":"channel2test","imageUrl":"image1.png"},{"id":"2","name":"channel2test" ,"imageUrl":"image2.png"}]}
模型类
class ChannelModel {
String channelID;
String channelName;
String imageUrl;
ChannelModel(this.channelID, this.channelName, this.imageUrl);
factory ChannelModel.parsingChannels(dynamic json) {
return ChannelModel(json['channelID'] as String,
json['channelName'] as String, json['imageUrl'] as String);
}
@override
String toString() {
return '{ ${this.channelID}, ${this.channelName}, ${this.imageUrl} }';
}
}
主块
try {
final response = await http.post(
url,
body: json.encode({
'action': 'getMyChannels',
'userID': userID,
'returnSecureToken': true,
}),
);
// print(jsonDecode(response.body));
var extractedData =
jsonDecode(response.body)['myChannels'] as List<dynamic>;
List<ChannelModel> channelObjects = extractedData
.map((cJson) => ChannelModel.parsingChannels(cJson))
.toList();
print(channelObjects);
channelObjects.forEach((Data) {
print('test');
});
结果如下...
print(channelObjects) > outputs > []
print('test') > not working , channelObjects not looping
解决方案
我建议将您对dart
课程的回应序列化。访问您想要的数据会容易得多。
class ApiResponse {
ApiResponse({
required this.myChannels,
});
List<MyChannel> myChannels;
factory ApiResponse.fromJson(Map<String, dynamic> json) => ApiResponse(
myChannels: List<MyChannel>.from(
json["myChannels"].map((x) => MyChannel.fromJson(x)),
),
);
}
class MyChannel {
MyChannel({
required this.id,
required this.name,
required this.imageUrl,
});
String id;
String name;
String imageUrl;
factory MyChannel.fromJson(Map<String, dynamic> json) => MyChannel(
id: json["id"],
name: json["name"],
imageUrl: json["imageUrl"],
);
}
然后你可以这样使用它:
final extractedData = ApiResponse.fromJson(json.decode(response.body) as Map<String, dynamic>);
并访问您想要的数据
extractedData.myChannels[0].id
extractedData.myChannels[0].name
extractedData.myChannels[0].imageUrl
for (var ch in extractedData.myChannels){
print(ch.id);
print(ch.name);
print(ch.imageUrl);
}
推荐阅读
- c - C:指针分配错误
- c# - 如何使用 Azure 函数或逻辑应用将数据保存到 sql 数据库中?
- reactjs - axios 不会将 post 数据发送到后端
- python - 有没有办法从 django 的 TemplateView 中的同一类中的另一个函数访问函数内部的变量
- c# - 用于 asp.net mvc 5 的 HtmlHelpr 和 asp.net core mvc 的 IHtmlHelper 的 .NET 标准扩展库
- bash - 被 bash 中的 globbing、变量替换和 find 命令的组合弄糊涂了
- git - 为什么我的第二个私有存储库没有使用我的 GitHub 部署密钥?
- typo3 - 在项目文件中而不是在后端编写打字稿
- python - 在全屏模式下在 Raspberry pi 上的背景图像上创建文本
- python - 如何切换到 iframe 窗口?