【问题标题】:flutter get json array颤振获取json数组
【发布时间】:2021-03-17 23:53:01
【问题描述】:

您好,我将此 JSON 作为字符串作为 API 调用的响应

{
    "friends": {
        "data": [],
        "summary": {
            "total_count": 42
        }
    },
    "id": "111111111111111"
}

我想获取 friends.datafriends.summary.total_count。 类似的东西:

for (int i = 0 ; i < friends.summary.total_count ; i++)
{
    myAmazingArray.pushback(friends.data[i]);
}

我认为 total_count 是数组中的内容数。 我也知道,为了获得“id”,我必须这样做:json['name']

【问题讨论】:

    标签: arrays json flutter dart


    【解决方案1】:

    您需要使用 dart:convert 中的 jsonDecode。实际上,如果数据中的长度相同,您甚至根本不需要使用 total_count 值。您可以简单地使用:

     import 'dart:convert';
    
     final Map<String, dynamic> dataMap = jsonDecode(json);
     final List<dynamic> friendsData = dataMap['friends']['data'];
    
     for(dynamic friend in friendsData) myAmazingArray.pushback(friend);
    

    我不知道data中包含什么样的内容,所以我建议你找出运行时类型(例如String,Map等)并在我上面的代码中交换'dynamic'这个词以改进代码质量。

    如果你想用 total_count 来做:

    final int total_count = dataMap['friends']['summary']['total_count'];
    
    for(int i=0; i<total_count; i++)
        myAmazingArray.pushback(friendsData[i]);
    

    【讨论】:

    • 谢谢,现在我知道如何使用 JSON:D 的不同深度了
    猜你喜欢
    • 2021-03-21
    • 2020-05-02
    • 2021-05-16
    • 2021-03-26
    • 2019-04-20
    • 2021-08-11
    • 2020-11-17
    • 2020-03-19
    • 2020-12-12
    相关资源
    最近更新 更多