解析json数组响应/颤动

Posted

技术标签:

【中文标题】解析json数组响应/颤动【英文标题】:Parsing json array response / flutter 【发布时间】: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 

【问题讨论】:

【参考方案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 更有用且易于理解。您可以阅读该软件包的文档

【讨论】:

以上是关于解析json数组响应/颤动的主要内容,如果未能解决你的问题,请参考以下文章

从 JSON 响应中解析两个不同对象的数组

如何从android中的php关联数组解析JSON响应?

在 JSON 响应中解析数组

Spray-Json:如何解析 Json 数组?

从json解析三个对象的数组

如何在颤动中解析此响应,并从 API 响应中的两个数组的文本字段中获取响应值? [关闭]