简体   繁体   English

未处理的异常:键入“列表”<dynamic> ' 不是 'SubJsonModel' 类型的子类型 - flutter</dynamic>

[英]Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'SubJsonModel' - flutter

Am trying to get a data from a json url but i get the error我试图从 json url 获取数据,但我得到了错误

Unhandled Exception: type 'List' is not a subtype of type 'SubJsonModel'未处理的异常:“List”类型不是“SubJsonModel”类型的子类型

main.dart main.dart

final String url = 'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json';
List<JsonModel> myModel = [];

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadData();
  }

  loadData() async {
  var res = await http.get(url, headers: {"Accept":"application/json"});
  if(res.statusCode == 200) {
    String resBody = res.body;
    var jsonDecode = json.decode(resBody);
    for(var data in jsonDecode) {
      myModel.add(JsonModel(data['cat_id'], data['category'], data['cat_subcategory']));
      setState(() {});
    }
      print(myModel[1].subCat.name);
  }else {
    print("Something went wrong!");
  }
  }

model.dart model.dart

class JsonModel {
  final String id;
  final String category;
  SubJsonModel subCat;

  JsonModel(this.id, this.category, this.subCat);
}

class SubJsonModel {
  final String name;
  final String image;

  SubJsonModel(this.name, this.image);
}

please how do i solve this请问我该如何解决这个问题

You can use https://app.quicktype.io/ to create the model.dart from a json.您可以使用https://app.quicktype.io/从 Z466Z35E630DAF44DBFA4C3F68F5399D8CZ.dart 创建 model.dart

To parse this JSON data, do final pieSingleChartInfo = pieSingleChartInfoFromJson(jsonString);要解析此 JSON 数据,请执行 final pieSingleChartInfo = pieSingleChartInfoFromJson(jsonString);

import 'dart:convert';

List<PieSingleChartInfo> pieSingleChartInfoFromJson(String str) => List<PieSingleChartInfo>.from(json.decode(str).map((x) => PieSingleChartInfo.fromJson(x)));

String pieSingleChartInfoToJson(List<PieSingleChartInfo> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class PieSingleChartInfo {
    PieSingleChartInfo({
        this.category,
        this.catId,
        this.catIcon,
        this.catSubcategory,
    });

    String category;
    String catId;
    String catIcon;
    List<CatSubcategory> catSubcategory;

    factory PieSingleChartInfo.fromJson(Map<String, dynamic> json) => PieSingleChartInfo(
        category: json["category"],
        catId: json["cat_id"],
        catIcon: json["cat_icon"] == null ? null : json["cat_icon"],
        catSubcategory: List<CatSubcategory>.from(json["cat_subcategory"].map((x) => CatSubcategory.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "category": category,
        "cat_id": catId,
        "cat_icon": catIcon == null ? null : catIcon,
        "cat_subcategory": List<dynamic>.from(catSubcategory.map((x) => x.toJson())),
    };
}

class CatSubcategory {
    CatSubcategory({
        this.subName,
        this.subImage,
    });

    String subName;
    String subImage;

    factory CatSubcategory.fromJson(Map<String, dynamic> json) => CatSubcategory(
        subName: json["sub_name"],
        subImage: json["sub_image"],
    );

    Map<String, dynamic> toJson() => {
        "sub_name": subName,
        "sub_image": subImage,
    };
}

I noted a few issues and corrected them based on the information you provided.我注意到了一些问题,并根据您提供的信息进行了更正。 Read the comments.阅读评论。 Add a sample response body to the question.向问题添加示例响应正文。

final String url =
    'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json';
List<JsonModel> myModel = [];

@override
void initState() {
  // TODO: implement initState
  super.initState();
  loadData();
}

loadData() async {
  var res = await http.get(url, headers: {"Accept": "application/json"});
  if (res.statusCode == 200) {
    String resBody = res.body;
    var jsonDecode = json.decode(resBody);
    for (var data in jsonDecode) {
      // first create SubJsonModel object
      var subCat = SubJsonModel(
          data['cat_subcategory']['name'], data['cat_subcategory']['image']);
      //use subCat to create JsonModel
      myModel.add(JsonModel(data['cat_id'], data['category'], subCat));
      setState(() {});
    }
    print(myModel[1].subCat.name);
  } else {
    print("Something went wrong!");
  }
}

So here what I do first create a model class with the help of this online tool .所以在这里我首先在这个在线工具的帮助下创建一个 model class 。 And then changed code like first save subcategory in one list and then passed it to the main list and then print然后更改代码,例如首先将子类别保存在一个列表中,然后将其传递给主列表,然后打印

Here is my loadData() method这是我的loadData()方法

final String url = 'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json';最终字符串 url = 'https://raw.githubusercontent.com/BrightCode1/ohms-json/master/categories.json'; List myModel = [];列出我的模型 = [];

  loadData() async {
    var res = await http.get(url, headers: {"Accept": "application/json"});
    if (res.statusCode == 200) {
      String resBody = res.body;
      var jsonDecode = json.decode(resBody);
      for (var data in jsonDecode) {


        List<CatSubcategory> subCate = [];   // Set a emoty list of CatSubcategory
         data['cat_subcategory'].map((x) {  // Here parsed the cat_subcategory data and simply add it into list
          return subCate.add(
              CatSubcategory(subName: x['sub_name'], subImage: x['sub_image']));
        }).toList();  // and this done for we get map data so convert this data toList();


        myModel.add(JsonModel(
            category: data['category'],
            catId: data['cat_id'],
            catIcon: data['cat_icon'],
            catSubcategory: subCate));
        setState(() {});
      }
      print(myModel[0].catSubcategory[0].subName);
    } else {
      print("Something went wrong!");
    }
  }

here is my model class这是我的model class

class JsonModel {
  JsonModel({
    this.category,
    this.catId,
    this.catIcon,
    this.catSubcategory,
  });

  String category;
  String catId;
  String catIcon;
  List<CatSubcategory> catSubcategory;

  factory JsonModel.fromJson(Map<String, dynamic> json) => JsonModel(
        category: json["category"],
        catId: json["cat_id"],
        catIcon: json["cat_icon"],
        catSubcategory: List<CatSubcategory>.from(
            json["cat_subcategory"].map((x) => CatSubcategory.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "category": category,
        "cat_id": catId,
        "cat_icon": catIcon,
        "cat_subcategory":
            List<dynamic>.from(catSubcategory.map((x) => x.toJson())),
      };
}

class CatSubcategory {
  CatSubcategory({
    this.subName,
    this.subImage,
  });

  String subName;
  String subImage;

  factory CatSubcategory.fromJson(Map<String, dynamic> json) => CatSubcategory(
        subName: json["sub_name"],
        subImage: json["sub_image"],
      );

  Map<String, dynamic> toJson() => {
        "sub_name": subName,
        "sub_image": subImage,
      };
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未处理的异常:键入“列表”<dynamic> &#39; 不是类型 &#39;Map 的子类型<String, dynamic> &#39; 在颤动中如何像这样发布 json obj - Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' in flutter how to post json obj like this 未处理的异常:键入“列表<dynamic> ' 不是 'Map 类型的子类型<string, dynamic> ' flutter 错误</string,></dynamic> - Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' flutter error 未处理的异常:键入“列表”<dynamic> ' 不是类型 'Map 的子类型<string, dynamic> ' 在飞镖/ flutter</string,></dynamic> - Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' in dart/ flutter 未处理的异常:键入“列表”<dynamic> &#39; 不是 &#39;List 类型的子类型<String> &#39; - Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>' 未处理的异常:键入“列表”<dynamic> ' 不是类型 'List 的子类型<model> '</model></dynamic> - Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<Model>' Flutter dart json 未处理的异常:InternalLinkedHashMap<string, dynamic> ' 不是类型 'List 的子类型<dynamic></dynamic></string,> - Flutter dart json Unhandled Exception: InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic> 未处理的异常:“String”类型不是“List”类型的子类型<dynamic> &#39; - Unhandled Exception: type 'String' is not a subtype of type 'List<dynamic>' 未处理的异常:InternalLinkedHashMap<string, dynamic> ' 不是类型 'List 的子类型<dynamic></dynamic></string,> - Unhandled Exception: InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic> 未处理的异常:类型 '_InternalLinkedHashMap<string, dynamic> ' 不是类型转换 int flutter 中类型 'OriginDestination' 的子类型</string,> - Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'OriginDestination' in type cast int flutter Flutter - 未处理的异常:未处理的错误类型“int”不是“日期时间”类型的子类型? - Flutter - Unhandled Exception: Unhandled error type 'int' is not a subtype of type 'DateTime?'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM