FlutterJson数组转换为List对象及Dio请求结果换为List对象

举报
yd_221104950 发表于 2020/12/01 00:36:29 2020/12/01
【摘要】 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, dynami...

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;
  }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

1.1.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"
  }
 ]

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

将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}");

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

或者用以下方法,更为简洁高效:

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
  • 3
  • 4
  • 5
  • 6

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); }
  }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

在上面的请求中,Dio返回的结果为List<dynamic>,我想要的结果是List<VideoInfo>,那么我们的思路就是:
1.因为拿回来的数据Response没有指定泛型,因此默认为dynamic,所以我们要将其类型转换回List<dynamic>,即:

response.data as List<dynamic>

  
 
  • 1

如果我们指定了Response的泛型为List<dynamic>,则不需要做这一步的工作,即Response<List<dynamic>>:

Response<List<dynamic>> response = await Dio().get( dataURL, options: Options(responseType: ResponseType.json), );

  
 
  • 1
  • 2
  • 3
  • 4

1.首先将List<dynamic>中的泛型dynamic转换成Map<String,dynamic>,也就是将List<dynamic>转成List<Map<String,dynamic>>,即e as Map<String, dynamic>,再利用我们的对象VideoInfo.fromJson()方法,生成我们的对象,即:

VideoInfo.fromJson((e as Map<String, dynamic>))

  
 
  • 1

完成的转换过程为:

 /// 解析数据
List<VideoInfo> list = (response.data as List<dynamic>) .map((e) => VideoInfo.fromJson((e as Map<String, dynamic>))) .toList();

  
 
  • 1
  • 2
  • 3
  • 4

转换好的结果是在迭代器Iterable<E>里的,所以我们可以用迭代器提供的接口toList()将结果转换为List对象。

2.总结

将JSON数组转成List对象的关键就是利用VideoInfo.fromJson(),将Map对象转成VideoInfo对象。这当种涉及到类型转换,尤其是dynamic类型的转换。要识别好各个变量的真实类型,这至为重要。

文章来源: blog.csdn.net,作者:WongKyunban,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/weixin_40763897/article/details/109636129

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。