首页 > 解决方案 > 解析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 

标签: jsonflutterparsingmapping

解决方案


我建议将您对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);
}

推荐阅读