用Riverpod通过http获取JSON数据时报错:预期Coord类型却得到_JsonMap
这个报错的根本原因是你在Madrid.fromJson方法中,没有将JSON解析得到的_JsonMap(也就是coord字段对应的Map结构)转换为Coord实体类实例,而是直接把Map赋值给了声明为Coord类型的属性,导致类型不匹配。
排查解决步骤
1. 确认所有嵌套实体类的fromJson方法已正确实现
首先检查Coord、Weather、Main、Wind、Clouds、Sys这些嵌套的实体类,都要实现对应的fromJson构造方法,以Coord类为例,正确写法参考:
class Coord { final double lon; final double lat; Coord({required this.lon, required this.lat}); factory Coord.fromJson(Map<String, dynamic> json) { return Coord( lon: json['lon']?.toDouble() ?? 0.0, lat: json['lat']?.toDouble() ?? 0.0, ); } }
其他嵌套类按照相同规则实现fromJson构造即可。
2. 修正Madrid.fromJson中嵌套字段的赋值逻辑
不要直接把JSON返回的Map、List赋值给实体类属性,要调用对应嵌套类的fromJson做类型转换,数组类型的字段还要做遍历转换,正确的Madrid类参考写法:
class Madrid { final Coord coord; final List<Weather> weather; final String base; final Main main; final int visibility; final Wind wind; final Clouds clouds; final int dt; final Sys sys; final int timezone; final int id; final String name; final int cod; Madrid({ required this.coord, required this.weather, required this.base, required this.main, required this.visibility, required this.wind, required this.clouds, required this.dt, required this.sys, required this.timezone, required this.id, required this.name, required this.cod, }); factory Madrid.fromJson(Map<String, dynamic> json) { return Madrid( // 调用Coord.fromJson做类型转换,不要直接赋值json['coord'] coord: Coord.fromJson(json['coord']), // 数组类型遍历转成对应实体类实例 weather: (json['weather'] as List<dynamic>).map((item) => Weather.fromJson(item)).toList(), base: json['base'] ?? '', main: Main.fromJson(json['main']), visibility: json['visibility'] ?? 0, wind: Wind.fromJson(json['wind']), clouds: Clouds.fromJson(json['clouds']), dt: json['dt'] ?? 0, sys: Sys.fromJson(json['sys']), timezone: json['timezone'] ?? 0, id: json['id'] ?? 0, name: json['name'] ?? '', cod: json['cod'] ?? 0, ); } }
3. 修正代码笔误
你定义的FutureProvider里调用的是fetchMadridLocal(),但实际实现的请求方法名是fetchMadrid(),要改成一致才能正常触发请求:
final madridStateProvider = FutureProvider<Madrid>((ref) async { return fetchMadrid(); });
内容的提问来源于stack exchange,提问作者Diego jiménez
相关产品推荐
相关产品推荐

