【问题标题】:Parsing complex JSON with an array in flutter在颤动中用数组解析复杂的JSON
【发布时间】:2021-06-26 04:50:27
【问题描述】:

我想解析一个由数组组成的复杂 JSON API,它显示以下错误。 API有天气的详细信息,我想在控制台中显示时间和波高。

错误

E/flutter ( 5675): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'

E/flutter ( 5675): #0      _JsonDemoState.getJsonData
package:bottom_nav/APISample/JsonParsing.dart:25
E/flutter ( 5675): <asynchronous suspension>
E/flutter ( 5675):

这是我需要解析的json。

    {
    "hours": [
        {
            "time": "2021-03-23T00:00:00+00:00",
            "waveHeight": {
                "icon": 1.35,
                "meteo": 1.25,
                "noaa": 0.97,
                "sg": 1.25
            }
        },
        {
            "time": "2021-03-23T01:00:00+00:00",
            "waveHeight": {
                "icon": 1.36,
                "meteo": 1.26,
                "noaa": 0.97,
                "sg": 1.26
            }
        }
]
}

这是解析json的函数

void getJsonData() async {
    
    String url2 =
        'https://api.stormglass.io/v2/weather/point?lat=5.9774&lng=80.4288&params=waveHeight&start=2021-03-23&end=2021-03-24';

    String apiKey =
        'the API key';

    Response response = await get(Uri.parse(url2),
        headers: {HttpHeaders.authorizationHeader: apiKey});
    

    List data = jsonDecode(response.body);
    data.forEach((element) {
      Map obj = element;
      String hours = obj['hours'];
      Map wave = obj['waveHeight'];
      int icon = wave['icon'];
      print(icon);
    });
  }

【问题讨论】:

    标签: json api flutter flutter-dependencies rest


    【解决方案1】:

    response.body 的 JSON 反序列化将返回 Map 而不是 List,因此可以选择访问与“hours”键关联的值,并将其转换为 Map 的 List,键类型为 String,值类型为 dynamic .

    final mapList = data['hours'] as List<Map<String, dynamic>>;
      
    mapList.forEach((item) => print(item.values.last['icon']));
      
    

    【讨论】:

      【解决方案2】:

      你愿意试试这个

       var jsonData = jsonDecode(response.body);
          List data = jsonData["hours"];
      
          data.forEach((element) {
            Map obj = element;
            Map wave = obj['waveHeight'];
            double icon = wave['icon'];
            print(icon);
          });
      

      【讨论】:

      • ` E/flutter (4909): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] 未处理异常:SocketException:主机查找失败:'api.stormglass.io'(操作系统错误:没有与主机名关联的地址,errno = 7) `New 显示此错误
      • 您的测试设备连接到互联网了吗?
      • 这是另一个问题,SocketException。您的 api 错误或关闭
      • 出了什么问题?
      • 模拟器问题。清理构建项目,它是成功的
      猜你喜欢
      • 1970-01-01
      • 2021-10-10
      • 2020-08-14
      • 2019-09-06
      • 2016-04-21
      • 2021-08-18
      • 2021-11-13
      • 1970-01-01
      • 2019-08-31
      相关资源
      最近更新 更多