FlutterJson数组转换为List对象及Dio请求结果换为List对象
1.实体类
class VideoInfo {
String body;
int id;
String title;
int userId;
VideoInfo({this.body, this.id, this.title, this.userId});
factory VideoInfo.fromJson(Map<String, dynamic> json) {
return VideoInfo(
body: json['body'],
id: json['id'],
title: json['title'],
userId: json['userId'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['body'] = this.body;
data['id'] = this.id;
data['title'] = this.title;
data['userId'] = this.userId;
return data;
}
}
2.Json数组转List对象
假设我们的Json数组是这样的:
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
]
将json数组转为List对象的方法如下:
String jsonStr =
'[{"userId": 1,"id": 1,"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit","body": "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto"},{"userId": 1,"id": 2,"title": "qui est esse","body": "est rerum tempore vitae sequi sint nihil reprehenderit dolor beatae ea dolores neque fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis qui aperiam non debitis possimus qui neque nisi nulla"}]';
/// 或json.decode(s); 实际的类型是List<dynamic>
var listDynamic = jsonDecode(jsonStr);
/// 显式类型转换, List<dynamic> -> List<Map<String, dynamic>>
List<Map<String, dynamic>> listMap =
new List<Map<String, dynamic>>.from(listDynamic);
List<VideoInfo> M = new List();
listMap.forEach((m) => M.add(VideoInfo.fromJson(m)));
print("数据为${M[0].title}");
或者用以下方法,更为简洁高效:
String jsonStr =
'[{"userId": 1,"id": 1,"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit","body": "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto"},{"userId": 1,"id": 2,"title": "qui est esse","body": "est rerum tempore vitae sequi sint nihil reprehenderit dolor beatae ea dolores neque fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis qui aperiam non debitis possimus qui neque nisi nulla"}]';
/// 或json.decode(s); 实际的类型是List<dynamic>
var listDynamic = jsonDecode(jsonStr);
List<VideoInfo> MM = (listDynamic as List<dynamic>).map((e) => VideoInfo.fromJson((e as Map<String,dynamic>))).toList();
print("数据为${MM[0].title}");
1.2.Dio请求结果转List对象
loadData() async {
String dataURL = "https://jsonplaceholder.typicode.com/posts";
try {
Response response = await Dio().get(
dataURL,
options: Options(responseType: ResponseType.json),
);
if (response.statusCode == 200) {
print("响应数据:${response.data}");
/// 更新UI
setState(() {
/// 解析数据
List<VideoInfo> list = (response.data as List<dynamic>)
.map((e) => VideoInfo.fromJson((e as Map<String, dynamic>)))
.toList();
print("My Data:${list[0].title}");
});
} else {
print("失败${response.statusCode}");
}
} catch (e) {
print(e);
}
}
在上面的请求中,Dio返回的结果为List,我想要的结果是List,那么我们的思路就是:
1.因为拿回来的数据Response没有指定泛型,因此默认为dynamic,所以我们要将其类型转换回List,即:
response.data as List<dynamic>
如果我们指定了Response的泛型为List,则不需要做这一步的工作,即Response<List>:
Response<List<dynamic>> response = await Dio().get(
dataURL,
options: Options(responseType: ResponseType.json),
);
1.首先将List中的泛型dynamic转换成Map<String,dynamic>,也就是将List转成List<Map<String,dynamic>>,即e as Map<String, dynamic>,再利用我们的对象VideoInfo.fromJson()方法,生成我们的对象,即:
VideoInfo.fromJson((e as Map<String, dynamic>))
完成的转换过程为:
/// 解析数据
List<VideoInfo> list = (response.data as List<dynamic>)
.map((e) => VideoInfo.fromJson((e as Map<String, dynamic>)))
.toList();
2.总结
将JSON数组转成List对象的关键就是利用VideoInfo.fromJson(),将Map对象转成VideoInfo对象。这当种涉及到类型转换,尤其是dynamic类型的转换。要识别好各个变量的真实类型,这至为重要。
参考
版权声明:本文为CSDN博主「WongKyunban」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_40763897/article/details/109636129