我正在扑朔迷离地学习TDD(测试驱动开发)。在这里,我试图解析我的JSON数据,但是每次运行测试时,我都会得到一个错误提示。
错误:类型'String'不是'索引'的类型'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
}
任何帮助都会很棒。
答案 0 :(得分: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']
不像map那样返回,它是一个数组。它以[0]
为第一个值。