Flutter資料解析Map格式

風吹過的昕發表於2021-07-20

問題描述:

在flutter端進行網路資料解析時,後端返回一個帶有jsonArray格式的複雜Map物件,咋一看有點懵,返回的資料如下:

"data":{
    "1908":[
        {
            "id":"1099",
            "createDate":"2021-05-31 00:41:12",
            "modifyDate":"2021-06-01 10:57:19",
            "orders":0,
            "beginDate":"2021-05-31 00:00:00",
            "content":"",
            "endDate":"2031-05-31 23:59:59",
            "imgPath":"https://xxx/upload/image/20210601/qpN5dnoh3.png",
            "title":"單個廣告1",
          
            "adPosition":"1908",
            "adPositionName":"第一banner"
        }
    ],
    "1909":[
        {
            "id":"1157",
            "createDate":"2021-06-03 16:38:18",
            "modifyDate":"2021-07-14 13:54:31",
            "orders":0,
            "beginDate":"2021-07-16 00:00:00",
            "content":"",
            "endDate":"2021-07-16 23:59:59",
            "imgPath":"https://xxx/upload/image/20210714/Mp35LWiP3.jpg",
            "title":"輪播廣告1",
          
            "adPosition":"1909",
            "adPositionName":"第二banner"
        },
        {
            "id":"1211",
            "createDate":"2021-06-24 08:50:38",
            "modifyDate":"2021-07-14 13:53:03",
            "orders":0,
            "beginDate":"2021-07-16 00:00:00",
            "content":"",
            "endDate":"2021-07-16 23:59:59",
            "imgPath":"https:/xxx/upload/image/20210714/qpGiCkV-3.png",
            "title":"輪播廣告2",
   
            "adPosition":"1909",
            "adPositionName":"第二banner"
        
        }
    ]
}
複製程式碼

解決方案:

仔細分析拆解資料格式型別,突然覺得很簡單,這資料格式不就是Map<String,List>mapData嗎? mapData.forEach((key,value){ //key就是1908,value就是List資料。 })

廢話不多說,直接上程式碼

@JsonSerializable()
class FindAdByIdResponse extends BaseJsonResponse {
  Map<String, List<FindAdByIdData>> data;

  FindAdByIdResponse(int code, String message, DateTime serverTime, this.data) : super(code, message, serverTime);

  factory FindAdByIdResponse.fromJson(Map<String, dynamic> json) => _$FindAdByIdResponseFromJson(json);

  Map<String, dynamic> toJson() => _$FindAdByIdResponseToJson(this);
}
複製程式碼
FindAdByIdResponse response = FindAdByIdResponse.fromJson(data.data);
Map<String, List<FindAdByIdData>>mapData = response.data;
mapData.forEach((key, value) { 
  //key就是1908,value就是List<FindAdByIdData>
});
複製程式碼

小結

如果此文有所幫助,還請您給點個贊

相關文章