Json解析失败_InternalLinkedHashMap <String,dynamic>'不是'String类型的子类型

时间:2019-12-17 07:50:01

标签: flutter

我想解析此API响应:

{
  "count": 2,
  "next": null,
  "previous": null,
  "results": [
    {
      "image": "https://asasas"
    },
    {
      "image": "https://xxzx"
    }
  ]
}

型号:

class SliderModel {
  final String count;
  final List<Result> results;

  SliderModel({this.count, this.results});

  factory SliderModel.fromJson(Map<String, dynamic> parsedJson) {
    var list = parsedJson['results'] as List;
    List<Result> imagesList = list.map((i) => Result.fromJson(i)).toList();

    return SliderModel(
      count: parsedJson['count'],
      results: imagesList
    );
  }
}

class Result {
  final String image;

  Result({this.image});

  factory Result.fromJson(Map<String, dynamic> parsedJson) {
    return Result(
      image: parsedJson['image']
    );
  }
}

和调用方法:

Future<SliderModel> _loadSlider() async{
    try {
      Response response = await Dio().get("https://dasas/api/slider/");
      print("11111");   // printing 
      SliderModel slider = SliderModel.fromJson(json.decode(response.data));
      print("2222222222222");  // doesn't print throws error
      return slider;
    } catch (e) {
      print("error $e");
    }
  }

当我尝试运行此代码时,它将引发以下消息:

 type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' 

2 个答案:

答案 0 :(得分:2)

看看这种方法:

factory SliderModel.fromJson(Map<String, dynamic> parsedJson) {
    var list = parsedJson['results'] as List;
    List<Result> imagesList = list.map((i) => Result.fromJson(i)).toList();

    return SliderModel(
      count: parsedJson['count'],
      results: imagesList
    );
  }

list是动态列表(List <动态>)。因此,.map之后仍是列表。

解决方案:指定地图的返回类型。

List<Result> imagesList = list.map<Result>((i) => Result.fromJson(i)).toList();

答案 1 :(得分:1)

如果以下行引发了您提到的错误,那么您无需对其进行json.decode解码,因为它已经是Map,而不是JSON字符串。

SliderModel slider = SliderModel.fromJson(json.decode(response.data));

替换为:

SliderModel slider = SliderModel.fromJson(response.data);

让我知道它是否对您有用,以防万一它不起作用,请发表评论,如果它不起作用,请不要忘记接受并投票赞成答案。