类型错误:将JSON数据解析为Flutter模型对象时发生错误。

huangapple go评论113阅读模式
英文:

Type error when parsing JSON data into Flutter model objects

问题

我正在开发一个Flutter项目,需要将JSON数据解析为模型对象。JSON结构包括嵌套对象和数组。我有三个模型类:UserModel、AbilityModel和SkillModel。

UserModel类具有AbilityModel对象的列表,每个AbilityModel对象都有一个SkillModel对象的列表。

当我尝试将JSON数据反序列化为模型对象时,遇到了以下错误:

type 'List<dynamic>' is not a subtype of type 'Iterable<Map<String, dynamic>>'

我怀疑问题与"ability"字段的JSON结构有关,它是一个对象数组。但是,我不确定如何在我的代码中正确处理它。

这是我模型类的简化版本:

// UserModel
class UserModel {
  int id;
  String name;
  List<AbilityModel> abilities;

  UserModel({required this.id, required this.name, required this.abilities});

  UserModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    abilities = (json['ability'] as List<dynamic>)
        .map((ability) => AbilityModel.fromJson(ability))
        .toList();
  }
}

// AbilityModel
class AbilityModel {
  int id;
  List<SkillModel> skills;

  AbilityModel({required this.id, required this.skills});

  AbilityModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    skills = (json['skills'] as List<dynamic>)
        .map((skill) => SkillModel.fromJson(skill))
        .toList();
  }
}

// SkillModel
class SkillModel {
  int id;
  String name;

  SkillModel({required this.id, required this.name});

  SkillModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
  }
}

这是用户存储库的代码:

class UserRepository {
  Future<List<UserModel>> getUsers() async {
    final response = await http.get(Uri.parse('https://example.com/users'));

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body)['data']['users'];
      List<UserModel> users = [];
      for (var userData in data) {
        UserModel user = UserModel.fromJson(userData);
        users.add(user);
      }
      return users;
    } else {
      throw Exception('Failed to load users');
    }
  }
}

这是我尝试解析的JSON数据示例:

{
  "data": {
    "users": [
      {
        "id": 1,
        "name": "John Doe",
        "ability": [
          {
            "id": 1,
            "skills": [
              {
                "id": 1,
                "name": "Skill1"
              }
            ]
          },
          {
            "id": 2,
            "skills": [
              {
                "id": 2,
                "name": "Skill2"
              }
            ]
          }
        ]
      },
      {
        "id": 2,
        "name": "Jane Smith",
        "ability": [
          {
            "id": 3,
            "skills": [
              {
                "id": 3,
                "name": "Skill3"
              }
            ]
          },
          {
            "id": 4,
            "skills": [
              {
                "id": 4,
                "name": "Skill4"
              }
            ]
          }
        ]
      }
    ]
  }
}

请问是否还有其他问题需要帮助解决?

英文:

I'm working on a Flutter project where I need to parse JSON data into model objects. The JSON structure includes nested objects and arrays. I have three model classes: UserModel, AbilityModel, and SkillModel.

The UserModel class has a list of AbilityModel objects, and each AbilityModel object has a list of SkillModel objects.

When I try to deserialize the JSON data into the model objects, I encounter the following error:

type &#39;List&lt;dynamic&gt;&#39; is not a subtype of type &#39;Iterable&lt;Map&lt;String, dynamic&gt;&gt;&#39;

I suspect the issue is related to the JSON structure of the "ability" field, which is an array of objects. However, I'm not sure how to properly handle it in my code.

Here's a simplified version of my model classes:

// UserModel
class UserModel {
  int id;
  String name;
  List&lt;AbilityModel&gt; abilities;

  UserModel({required this.id, required this.name, required this.abilities});

  UserModel.fromJson(Map&lt;String, dynamic&gt; json) {
    id = json[&#39;id&#39;];
    name = json[&#39;name&#39;];
    abilities = (json[&#39;ability&#39;] as List&lt;dynamic&gt;)
        .map((ability) =&gt; AbilityModel.fromJson(ability))
        .toList();
  }
}

// AbilityModel
class AbilityModel {
  int id;
  List&lt;SkillModel&gt; skills;

  AbilityModel({required this.id, required this.skills});

  AbilityModel.fromJson(Map&lt;String, dynamic&gt; json) {
    id = json[&#39;id&#39;];
    skills = (json[&#39;skills&#39;] as List&lt;dynamic&gt;)
        .map((skill) =&gt; SkillModel.fromJson(skill))
        .toList();
  }
}

// SkillModel
class SkillModel {
  int id;
  String name;

  SkillModel({required this.id, required this.name});

  SkillModel.fromJson(Map&lt;String, dynamic&gt; json) {
    id = json[&#39;id&#39;];
    name = json[&#39;name&#39;];
  }
}

And here's the user repository:

class UserRepository {
  Future&lt;List&lt;UserModel&gt;&gt; getUsers() async {
    final response = await http.get(Uri.parse(&#39;https://example.com/users&#39;));

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body)[&#39;data&#39;];
      List&lt;UserModel&gt; users = [];
      for (var userData in data) {
        UserModel user = UserModel.fromJson(userData);
        users.add(user);
      }
      return users;
    } else {
      throw Exception(&#39;Failed to load users&#39;);
    }
  }
}

And here's an example of the JSON data I'm trying to parse:

{
  &quot;data&quot;: {
    &quot;users&quot;: [
      {
        &quot;id&quot;: 1,
        &quot;name&quot;: &quot;John Doe&quot;,
        &quot;ability&quot;: [
          {
            &quot;id&quot;: 1,
            &quot;skills&quot;: [
                &quot;id&quot;: 1,
                &quot;name&quot;: &quot;Skill1&quot;
            ]
          },
          {
            &quot;id&quot;: 2,
            &quot;skills&quot;: [
                &quot;id&quot;: 2,
                &quot;name&quot;: &quot;Skill2&quot;
            ]
          }
        ]
      },
      {
        &quot;id&quot;: 2,
        &quot;name&quot;: &quot;Jane Smith&quot;,
        &quot;ability&quot;: [
          {
            &quot;id&quot;: 3,
            &quot;skills&quot;: [
                &quot;id&quot;: 3,
                &quot;name&quot;: &quot;Skill3&quot;
            ]
          },
          {
            &quot;id&quot;: 4,
            &quot;skills&quot;: [
                &quot;id&quot;: 4,
                &quot;name&quot;: &quot;Skill4&quot;
            ]
          }
        ]
      }
    ]
  }
}

I would greatly appreciate any guidance on how to properly deserialize the JSON data into the model objects and resolve this type error. Thank you in advance for your help!

答案1

得分: 0

你的JSON代码格式错误

{
    "data": {
        "users": [
            {
                "id": 1,
                "name": "John Doe",
                "ability": [
                    {
                        "id": 1,
                        "skills": {
                            "id": 1,
                            "name": "Skill1"
                        }
                    },
                    {
                        "id": 2,
                        "skills": {
                            "id": 2,
                            "name": "Skill2"
                        }
                    }
                ]
            },
            {
                "id": 2,
                "name": "Jane Smith",
                "ability": [
                    {
                        "id": 3,
                        "skills": {
                            "id": 3,
                            "name": "Skill3"
                        }
                    },
                    {
                        "id": 4,
                        "skills": {
                            "id": 4,
                            "name": "Skill4"
                        }
                    }
                ]
            }
        ]
    }
}

Dart模型

class Random {
  Data? data;

  Random({this.data});

  Random.fromJson(Map<String, dynamic> json) {
    data = json['data'] != null ? new Data.fromJson(json['data']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.data != null) {
      data['data'] = this.data!.toJson();
    }
    return data;
  }
}

class Data {
  List<Users>? users;

  Data({this.users});

  Data.fromJson(Map<String, dynamic> json) {
    if (json['users'] != null) {
      users = <Users>[];
      json['users'].forEach((v) {
        users!.add(new Users.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.users != null) {
      data['users'] = this.users!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Users {
  int? id;
  String? name;
  List<Ability>? ability;

  Users({this.id, this.name, this.ability});

  Users.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    if (json['ability'] != null) {
      ability = <Ability>[];
      json['ability'].forEach((v) {
        ability!.add(new Ability.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    if (this.ability != null) {
      data['ability'] = this.ability!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Ability {
  int? id;
  Skills? skills;

  Ability({this.id, this.skills});

  Ability.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    skills =
        json['skills'] != null ? new Skills.fromJson(json['skills']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    if (this.skills != null) {
      data['skills'] = this.skills!.toJson();
    }
    return data;
  }
}

class Skills {
  int? id;
  String? name;

  Skills({this.id, this.name});

  Skills.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    return data;
  }
}
英文:

Your json code format is wrong

{
&quot;data&quot;: {
&quot;users&quot;: [
{
&quot;id&quot;: 1,
&quot;name&quot;: &quot;John Doe&quot;,
&quot;ability&quot;: [
{
&quot;id&quot;: 1,
&quot;skills&quot;: {
&quot;id&quot;: 1,
&quot;name&quot;: &quot;Skill1&quot;
}
},
{
&quot;id&quot;: 2,
&quot;skills&quot;: {
&quot;id&quot;: 2,
&quot;name&quot;: &quot;Skill2&quot;
}
}
]
},
{
&quot;id&quot;: 2,
&quot;name&quot;: &quot;Jane Smith&quot;,
&quot;ability&quot;: [
{
&quot;id&quot;: 3,
&quot;skills&quot;: {
&quot;id&quot;: 3,
&quot;name&quot;: &quot;Skill3&quot;
}
},
{
&quot;id&quot;: 4,
&quot;skills&quot;: {
&quot;id&quot;: 4,
&quot;name&quot;: &quot;Skill4&quot;
}
}
]
}
]
}
}

Dart model

class Random {
Data? data;
Random({this.data});
Random.fromJson(Map&lt;String, dynamic&gt; json) {
data = json[&#39;data&#39;] != null ? new Data.fromJson(json[&#39;data&#39;]) : null;
}
Map&lt;String, dynamic&gt; toJson() {
final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;();
if (this.data != null) {
data[&#39;data&#39;] = this.data!.toJson();
}
return data;
}
}
class Data {
List&lt;Users&gt;? users;
Data({this.users});
Data.fromJson(Map&lt;String, dynamic&gt; json) {
if (json[&#39;users&#39;] != null) {
users = &lt;Users&gt;[];
json[&#39;users&#39;].forEach((v) {
users!.add(new Users.fromJson(v));
});
}
}
Map&lt;String, dynamic&gt; toJson() {
final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;();
if (this.users != null) {
data[&#39;users&#39;] = this.users!.map((v) =&gt; v.toJson()).toList();
}
return data;
}
}
class Users {
int? id;
String? name;
List&lt;Ability&gt;? ability;
Users({this.id, this.name, this.ability});
Users.fromJson(Map&lt;String, dynamic&gt; json) {
id = json[&#39;id&#39;];
name = json[&#39;name&#39;];
if (json[&#39;ability&#39;] != null) {
ability = &lt;Ability&gt;[];
json[&#39;ability&#39;].forEach((v) {
ability!.add(new Ability.fromJson(v));
});
}
}
Map&lt;String, dynamic&gt; toJson() {
final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;();
data[&#39;id&#39;] = this.id;
data[&#39;name&#39;] = this.name;
if (this.ability != null) {
data[&#39;ability&#39;] = this.ability!.map((v) =&gt; v.toJson()).toList();
}
return data;
}
}
class Ability {
int? id;
Skills? skills;
Ability({this.id, this.skills});
Ability.fromJson(Map&lt;String, dynamic&gt; json) {
id = json[&#39;id&#39;];
skills =
json[&#39;skills&#39;] != null ? new Skills.fromJson(json[&#39;skills&#39;]) : null;
}
Map&lt;String, dynamic&gt; toJson() {
final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;();
data[&#39;id&#39;] = this.id;
if (this.skills != null) {
data[&#39;skills&#39;] = this.skills!.toJson();
}
return data;
}
}
class Skills {
int? id;
String? name;
Skills({this.id, this.name});
Skills.fromJson(Map&lt;String, dynamic&gt; json) {
id = json[&#39;id&#39;];
name = json[&#39;name&#39;];
}
Map&lt;String, dynamic&gt; toJson() {
final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;();
data[&#39;id&#39;] = this.id;
data[&#39;name&#39;] = this.name;
return data;
}
}

huangapple
  • 本文由 发表于 2023年6月26日 11:21:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76553339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定