【问题标题】:Dart Error: type 'List<dynamic>' is not a subtype of type 'String' in retrieving JSON Object within an ObjectDart 错误:在对象中检索 JSON 对象时,类型“List<dynamic>”不是“String”类型的子类型
【发布时间】:2021-10-21 09:29:04
【问题描述】:

我是 Dart 和 Flutter 的新手。

我正在尝试从本地 JSON 文件访问和打印某些信息。这是我的 myPet.json 文件的结构:

{
    "person": 
    [
        {
            "user_id": 23,
            "user_name": "Joe Hann",
            "user_dob": 1998,
            "pets": 
            [
                {
                    "id": 1,
                    "name": "Fifi",
                    "type": "Cat",
                    "attribute": ["Cute", "Black", "Caring"],
                    "likes": 
                    {
                        "hobbies": ["Play Ball", "Outing", "Sleep"],
                        "food": ["Whiskas", "PowerCat", "Fried Fish"]
                    },
                    "dateAdopted": "2020-10-10 11:25:02.155"
                },
                {
                    "id": 2,
                    "name": "Dongo",
                    "type": "Dog",
                    "attribute": ["Ferocious", "Loyal", "Big"],
                    "likes": 
                    {
                        "hobbies": ["Barking", "Eating", "Sleep"],
                        "food": ["Chicken", "Biscuit"]
                    },
                    "dateAdopted": "2020-8-10 8:10:09.392"
                }
            ]
        },
        {
            "user_id": 17,
            "user_name": "Sam Doll",
            "user_dob": 1995,
            "pets": 
            [
                {
                    "id": 13,
                    "name": "Gola",
                    "type": "Fish",
                    "attribute": ["Red", "Small", "Speeder"],
                    "likes": 
                    {
                        "hobbies": ["Swimming", "Blurbing"],
                        "food": ["Bread", "PowerCat"]
                    },
                    "dateAdopted": "2021-2-20 11:00:08.165"
                }
            ]
        }
    ]  
}

这是我的 Dart 代码:

import "dart:convert"; //for json conversion
import "dart:io"; //for input output local file

void main() {

  String jsonData = new File('myPet.json').readAsStringSync();

  List<Person> _listPerson = [];
  _listPerson = Person.allPersonFromJson(jsonData);

  print("List of Person:-");
  for(int i=0; i<_listPerson.length; i++)
  {
    print(_listPerson[i].user_id);
    print(_listPerson[i].user_name);
    print(_listPerson[i].user_dob);
    print("");
    print("Pets:");
    for(int j =0;j<_listPerson[i].pet.length; j++)
    {
      print(_listPerson[i].pet[j].id);
      print(_listPerson[i].pet[j].name);
      print(_listPerson[i].pet[j].type);
      print("Attributes:-");
      for(int k=0;k<_listPerson[i].pet[j].attribute.length;k++)
      {
        print(_listPerson[i].pet[j].attribute[k]);
      }
    print("");
    }
    print("");
    print("");
  }

}

class Person{
  final int user_id;
  final String user_name;
  final int user_dob;
  final List<Pet> pet;

  Person ({
    required this.user_id, 
    required this.user_name, 
    required this.user_dob,
    required this.pet});

  static List<Person> allPersonFromJson(String jsonData) {
    List<Person> person = [];

    json.decode(jsonData)['person'].forEach((data) => person.add(_mapPerson(data)));
    return person;
  }

  static Person _mapPerson(Map<String, dynamic> map){
    final user_id = map['user_id'] as int?; //required but nullable int with exception
    if (user_id == null) {throw UnsupportedError('Invalid data: $map -> "id" is missing');}
    final user_name = map['user_name'] as String?; //required but nullable String with exception
    if (user_name == null) {throw UnsupportedError('Invalid data: $map -> "name" is missing');}
    final user_dob = map['user_dob'] as int;
    final pet = Pet.allPetFromJson(map['pets']);

    return new Person(
      user_id: user_id,
      user_name: user_name,
      user_dob: user_dob,
      pet: pet
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'user_id': user_id,
      'user_name': user_name,
      'user_dob': user_dob,
      'pet': pet
    };
  }
}

class Pet{
  final int id;
  final String name;
  final String type;
  final List<String> attribute;

  Pet ({
    required this.id, 
    required this.name, 
    required this.type,
    required this.attribute});

  static List<Pet> allPetFromJson(String jsonData) {
    List<Pet> pet = [];

    json.decode(jsonData)['person']['pets'].forEach((data) => pet.add(_mapPet(data)));
   
    return pet;
  }

  static Pet _mapPet(Map<String, dynamic> map){
    final id = map['id'] as int?; //required but nullable int with exception
    if (id == null) {throw UnsupportedError('Invalid data: $map -> "pet id" is missing');}
    final name = map['name'] as String?; //required but nullable String with exception
    if (name == null) {throw UnsupportedError('Invalid data: $map -> "pet name" is missing');}
    final type = map['type'] as String?; //required but nullable String with exception
    if (type == null) {throw UnsupportedError('Invalid data: $map -> "pet type" is missing');}
    final attribute = List<String>.from(map['attribute']);

    return new Pet(
      id: id,
      name: name,
      type: type,
      attribute: attribute
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'type': type,
      'attribute': attribute
    };
  }
}

我可以通过直接访问 Pet 对象来调用和打印 Pet 信息,而无需将其包含在 Person 对象中。但我想做的是尝试通过 Person 对象调用和打印 Pet 对象。但是我收到错误“类型'List'不是'String'类型的子类型”。

我该如何处理这种情况?

【问题讨论】:

    标签: json dart object


    【解决方案1】:

    我不知道allPersonFromJson方法是做什么的,但是你需要将String解析为Json才能访问数据:

    final json = await json.decode(string); // <-- in your case "jsonData"
    

    json["person"] 你有一个人员列表(List&lt;dynamic&gt;

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 2021-04-07
      • 2021-04-13
      • 2021-09-21
      • 2021-03-17
      • 2022-12-02
      • 1970-01-01
      • 2019-06-26
      • 2019-01-22
      相关资源
      最近更新 更多