【发布时间】: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]