服务器端返回数据:
[{"title":"空间","tags":["矩形房间","干湿分离","多开间进深"]},{"title":"手法","tags":["砖墙","铝膜","木模"]},{"title":"特征","tags":["落地窗","飘窗","普通窗","降板"]},{"title":"建筑","tags":["高层","别墅","复式","联排"]}]
自定义Bean对象如下:
class TagData { String title = ""; Listtags = []; TagData(); TagData.fromJson(Map map) { this.title = map["title"]; this.tags = (map["tags"] as List).map((e) => e.toString()).toList(); } Map toJson() => {"title": this.title, "tags": this.tags}; }
为方便使用自定义字符串接收服务器端返回的数据(十几种可以直接转换,可能不需要)
String jsonData=[{"title":"空间","tags":["矩形房间","干湿分离","多开间进深"]},{"title":"手法","tags":["砖墙","铝膜","木模"]},{"title":"特征","tags":["落地窗","飘窗","普通窗","降板"]},{"title":"建筑","tags":["高层","别墅","复式","联排"]}];
方法一、推荐解析如下:
ListtagDataList1 = jsonDecode(jsonData);//不建议直接使用List 接收,要先过渡一下 List tagDataList2 = tagDataList1.map((e) => TagData.fromJson(e)).toList(); //检验结果 tagDataList2.forEach((tagData) { print("=======tagData标题:::${tagData.title}=============="); List.generate(tagData.tags.length, (index) => print("=======tagData[$index]:::${tagData.tags[index]}==============")); });
结果如下:
到此处理结束.
方法二、我开始在解析的时候没有想到要过渡一下,直接使用List
ListtagDataList1 = jsonDecode(jsonData); tagDataList1.forEach((tagData) { print("=======tagData标题:::${tagData["title"]}=============="); List.generate(tagData["tags"].length, (index) => print("=======tagData[$index]:::${tagData["tags"][index]}==============")); });
结果也同方法一一样,这里代码不同之处在于要使用tagData["title"],tagData["tags"],而不是tagData.title,tagData.tags.这是因为Map还没转换成TagData对象,方法一中的过渡就是将Map转换成TagData对象.
方法二没有方法一使用起来方便.
方法三、开始还想到过另外一种方法,当时是因为还不清楚解析List<对象>的数据,就想着外面再套一层,使得对象中有一个数组字段,完整model如下:
class TagList { TagList(); Listlist = [];//这里的list要与服务端统一,一般情况下会叫data,我这里只是模拟 TagList.fromJson(Map map) { this.list = (map["list"] as List).map((e) => TagData.fromJson(e)).toList(); } Map toJson() => {"list": this.list}; } class TagData { String title = ""; List tags = []; TagData(); TagData.fromJson(Map map) { this.title = map["title"]; this.tags = (map["tags"] as List).map((e) => e.toString()).toList(); } Map toJson() => {"title": this.title, "tags": this.tags}; }
对于fromJson和toJson的理解这个链接有说明:https://blog.csdn.net/qq_34707150/article/details/125440101
使用代码:
String jsonData={"list":[{"title":"空间","tags":["矩形房间","干湿分离","多开间进深"]},{"title":"手法","tags":["砖墙","铝膜","木模"]},{"title":"特征","tags":["落地窗","飘窗","普通窗","降板"]},{"title":"建筑","tags":["高层","别墅","复式","联排"]}]}================= TagList tagList1 = TagList.fromJson(jsonDecode(jsonData)); tagList1.list.forEach((element) { print("=======element:::${element.title}=============="); List.generate(element.tags.length, (index) => print("=======element[$index]:::${element.tags[index]}==============")); });
运行也能得到方法一的结果,这个就有点小麻烦了,又套了一层,本来是不需要的,个人感觉最好的是方法一.