【问题标题】:ERROR: type 'String' is not a subtype of type 'int' of 'index' while using fromjson in flutter错误:在颤振中使用 fromjson 时,类型“String”不是“index”类型“int”的子类型
【发布时间】:2020-02-29 13:08:09
【问题描述】:

我正在学习 TDD(试驾开发)。在这里,我试图解析我的 JSON 数据,但每次运行测试时都会出现错误提示。

错误:'String' 类型不是 'index' 的 'int' 类型的子类型

这些是我的代码

weather_app_model_test.dart

  group('fromJson', () {
    test('should return a valid model', () async {
      final Map<String, dynamic> jsonMap =
          json.decode(fixture('weather_app.json'));
      final result = WeatherAppModel.fromJson(jsonMap);
      expect(result, tWeatherAppModel);
    });
  });

weather_app_model.dart

factory WeatherAppModel.fromJson(Map<String, dynamic> json) {
    return WeatherAppModel(
      weatherMain: json['weather']['main'],
      weatherDescription: json['weather']['description'],
      temp: json['main']['temp'],
      minTemp: json['main']['temp_min'],
      maxTemp: json['main']['temp_main'],
      country: json['sys']['country'],
    );
  }

fixtures/weather_app.json

{
  "coord": {
    "lon": 78,
    "lat": 20
  },
  "weather": [
    {
      "id": 500,
      "main": "Rain",
      "description": "light rain",
      "icon": "10d"
    }
  ],
  "base": "model",
  "main": {
    "temp": 301.51,
    "pressure": 1014,
    "humidity": 67,
    "temp_min": 301.51,
    "temp_max": 301.51,
    "sea_level": 1014,
    "grnd_level": 979
  },
  "wind": {
    "speed": 3.19,
    "deg": 77
  },
  "rain": {
    "3h": 1.81
  },
  "clouds": {
    "all": 45
  },
  "dt": 1572672029,
  "sys": {
    "country": "IN",
    "sunrise": 1572655775,
    "sunset": 1572696807
  },
  "timezone": 19800,
  "id": 1272596,
  "name": "Digras",
  "cod": 200
}

任何帮助都会很棒。

【问题讨论】:

  • 您的json['weather'] 是一个数组,而不是映射,因此您需要通过[] 运算符访问它,例如:json['weather'][0]

标签: json flutter dart tdd


【解决方案1】:
factory WeatherAppModel.fromJson(Map<String, dynamic> json) {
    return WeatherAppModel(
      weatherMain: json['weather'][0]['main'],
      weatherDescription: json['weather'][0]['description'],
      temp: json['main']['temp'],
      minTemp: json['main']['temp_min'],
      maxTemp: json['main']['temp_main'],
      country: json['sys']['country'],
    );
  }

这将解决您的问题。 json['weather'] 不像地图那样返回,它是一个数组。它以[0] 取第一个值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 2020-08-11
    • 2021-02-25
    • 2019-08-14
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多