【问题标题】:Parsing json array response / flutter解析json数组响应/颤动
【发布时间】:2021-11-13 05:24:44
【问题描述】:

按照本手册执行此操作 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 

【问题讨论】:

    标签: json flutter parsing mapping


    【解决方案1】:

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

    【讨论】:

    • 我喜欢你的方法,但我无法解决我的问题,不知道为什么,然后我花了更多时间,找到了一篇带有示例的文章并根据该文章更新了我的代码.但是它又不起作用,你能检查我的代码并说出你的想法吗?
    【解决方案2】:
    part 'example.g.dart';
    
    @JsonSerializable()
    class Channel{
      final String id;
      final String name;
      final String? imageUrl;
      Channel({required this.id, required this.name, this.imageUrl});
      factory Channel.fromJson(Map<String, dynamic> json) => _$ChannelFromJson(json);
      Map<String, dynamic> toJson() => _$ChannelToJson(this);
    }
    
    
    
    @JsonSerializable()
    class ChannelList{
      final List<Channel> myChannels;
      ChannelList({required this.myChannels});
      factory ChannelList.fromJson(Map<String, dynamic> json) => _$ChannelListFromJson(json);
      Map<String, dynamic> toJson() => _$ChannelListToJson(this);
    }
    

    最终提取数据 = ChannelList.fromJson(json.decode(response.body));

    https://pub.dev/packages/json_serializable

    使用 JsonSerializable 更有用且易于理解。您可以阅读该软件包的文档

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-20
      • 2021-08-15
      • 2020-11-27
      • 2023-03-08
      • 2012-04-18
      • 2021-06-26
      • 2019-08-31
      • 2017-09-23
      相关资源
      最近更新 更多