如何在颤振中解析这个复杂的json

Posted

技术标签:

【中文标题】如何在颤振中解析这个复杂的json【英文标题】:how to parse this complex json in flutter 【发布时间】:2021-08-18 05:54:06 【问题描述】:

帮我解析一下这个复杂的json数据..!!!

我收到这样的错误 类型“_InternalLinkedHashMap”不是类型“Iterable”的子类型

这是我的回应


    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        
            "id": 4,
            "user": 3,
            "memory": "I saw that you were perfect, and so I loved you. Then I saw that you were not perfect and I loved you even more.",
            "hashtags": [
                
                    "id": 10,
                    "hashtag": "#trend"
                ,
                
                    "id": 11,
                    "hashtag": "#honeymoon"
                
            ],
            "photos": [
                
                    "id": 8,
                    "photo": "http//IMG_1622365232437.png/"
                
            ],
            "connections": [],
            "likes": [],
            "views": [],
            "date": "2021-05-24",
            "time": "02:00:00",
            "created_at": "2021-05-30T09:00:35.172231Z",
            "fontfamily": "Pacifico",
            "is_liked": false,
            "is_bookmarked": false,
            "is_archived": false
        ,
        
            "id": 5,
            "user": 3,
            "memory": "I saw that you were perfect, and so I loved you. Then I saw that you were not perfect and I loved you even more.",
            "hashtags": [
                
                    "id": 12,
                    "hashtag": "#love"
                ,
                
                    "id": 13,
                    "hashtag": "#relationship"
                
            ],
            "photos": [
                
                    "id": 9,
                    "photo": "http://api/v1/user-media/posts/sample_aBlr8us.jpg/"
                ,
                
                    "id": 10,
                    "photo": "http://api/v1/user-media/posts/hannah-grace-9W-vKFq4oEM-unsplash_ngXrYYP.jpg/"
                
            ],
            "connections": [],
            "likes": [],
            "views": [],
            "date": "2021-05-26",
            "time": "16:35:00",
            "created_at": "2021-05-30T09:03:00.122267Z",
            "fontfamily": "Roboto",
            "is_liked": false,
            "is_bookmarked": false,
            "is_archived": false
        
    ]


我的型号代码

class UserPosts 
  int count;
  String next;
  String previous;
  List<Results> results;

  UserPosts(this.count, 
  this.next, this.previous,
   this.results
  );

  factory UserPosts.fromJson(Map<String, dynamic> json) 
    return new UserPosts(
      count: json['count'],
      next: json['next'],
      previous: json['previous'],
      results: parseResults(json),
    );
  

  static List<Results> parseResults(resultsJson) 
    var list = resultsJson['results'] as List;
    List<Results> resultsList =
        list.map((data) => Results.fromJson(data)).toList();
    return resultsList;
  


class Results 
  int id;
  int user;
  String memory;
  List<HashTags> hashtags;
  List<Photos> photos;
  List<String> connections;
  List<String> likes;
  List<String> views;
  String date;
  String time;
  String fontfamily;
  bool is_liked;
  bool is_bookmarked;
  bool is_archived;

  Results(
      this.id,
      this.user,
      this.memory,
      this.hashtags,
      this.photos,
      this.connections,
      this.likes,
      this.views,
      this.date,
      this.time,
      this.fontfamily,
      this.is_liked,
      this.is_bookmarked,
      this.is_archived
      );

  factory Results.fromJson(Map<String, dynamic> json) 
    var connectionsFromJson = json['connections'];
    List<String> connectionsList = connectionsFromJson.cast<String>();
    var likesFromJson = json['likes'];
    List<String> likesList = likesFromJson.cast<String>();
    var viewsFromJson = json['views'];
    List<String> viewsList = viewsFromJson.cast<String>();
    return new Results(
        id: json['id'] as int,
        user: json['user'],
        memory: json['memory'],
        hashtags: parseHashTags(json),
        photos: parseImages(json),
        connections: connectionsList,
        likes: likesList,
        views: viewsList,
        date: json['date'],
        time: json['time'],
        fontfamily: json['fontfamily'],
        is_liked: json['is_liked'],
        is_bookmarked: json['is_bookmarked'],
        is_archived: json['is_archived']);
  

  static List<HashTags> parseHashTags(hashTagsJson) 
    var list = hashTagsJson['hashtags'] as List;
    List<HashTags> hashtagsList =
        list.map((data) => HashTags.fromJson(data)).toList();
    return hashtagsList;
  

  static List<Photos> parseImages(imagesJson) 
    var list = imagesJson['photos'] as List;
    List<Photos> imagesList =
        list.map((data) => Photos.fromJson(data)).toList();
    return imagesList;
  


class HashTags 
  int id;
  String hashtag;

  HashTags(this.id, this.hashtag);

  factory HashTags.fromJson(Map<String, dynamic> json) 
    return new HashTags(id: json['id'] as int, hashtag: json['hashtag']);
  


class Photos 
  int id;
  String photo;

  Photos(this.id, this.photo);

  factory Photos.fromJson(Map<String, dynamic> json) 
    return new Photos(
      id: json['id'] as int,
      photo: json['photo']
    );
  


**这是我的获取代码。但我得到了这样的错误“类型'_InternalLinkedHashMap'不是'Iterable'类型的子类型

  List<UserPosts> list = [];

  Future fetchData() async 
    setState(() 
      loading = true;
    );

    print("YES");

    try 
      Map<String, String> headers = 
        "Accept": "application/json",
        "Authorization": "Bearer $token"
      ;
      // final jsonEndpoint = Uri.parse("http://api/v1/posts/");
      final jsonEndpoint = Uri.parse("$baseurl/user-memory/");
      final response = await http.get(jsonEndpoint, headers: headers);
      print(response.body);

      if (response.statusCode == 200) 
        final data = jsonDecode(response.body);
        setState(() 
          for (Map i in data) 
            list.add(UserPosts.fromJson(i));
          
          loading = false;
        );
       else 
        print("failed");
      
     catch (e) 
      print(e.toString());
    
  

【问题讨论】:

【参考方案1】:

这是错误 var list = resultsJson['results'] as List; 的原因,它不是类型“Iterable”的子类型

以下代码示例:

static List<Results> parseResults(resultsJson) 
    var list = List<Results>();
    resultsJson['results'].forEach((v) 
        list.add(Results.fromJson(v));
      );
    return list;
  

【讨论】:

以上是关于如何在颤振中解析这个复杂的json的主要内容,如果未能解决你的问题,请参考以下文章

如何在颤振中解析json?

如何在颤振中解析json

如何继续在颤振中接收 JSON 数组并解析它?

如何使用我的图像在本地的颤振解析 json 文件中的图像?

在颤振中将请求复杂的json发布到api

如何从http POST请求结果颤振在listview builder上显示数据