当前位置: 首页 > 知识库问答 >
问题:

类型列表不是类型转换中映射类型的子类型

壤驷涛
2023-03-14

我在尝试使用JSON_serializable序列化从internet获取的复杂JSON并使用FutureProvider将它们连接在一起时遇到了这个问题。这是json文件,

{
  "data": {
    "quiz": {
      "stats": {
        "played": 6691,
        "totalPlayers": "29553"
      },
      "publishedVersion": "5a13431202b92110003fdb92",
      "_id": "5a133e2302b92110003fd8ef",
      "createdBy": {
        "local": {
          "username": "jshutt"
        },
        "occupation": "teacher_school"
      }, //createdBy
      "info": {
        "name": "Proportional Relationships",
        "image": "https://quizizz.com/media/resource/gs/quizizz-media/quizzes/L2FwcGhvc3RpbmdfcHJvZC9ibG9icy9BRW5CMlVyNUFUSlN0VXhVSzcxY1hHZGN4UmJYVEdiWHRpeXBCcmVvQXhwT0JhckZwdnhBdkw4cHFqYjNVNktJSnlwSEdtUlJubV9Nc2Qxck51Z2Z5ampNSzJWb09Qek1tU0Joc0NaSUZtdGNyYzlQN1ZUQWREQS5EOUxuUGh3MUxaZzk0MUYz",
        "subjects": [
          "Mathematics"
        ],
        "topics": [
          "Pre-algebra"
        ],
        "subtopics": [
          "Proportional relationships",
          "Constant of Proportionality",
          "proportional graphs",
          "proportion equations"
        ],
        "questions": [
          {
            "structure": {
              "kind": "MCQ",
              "query": {
                "media": [
                  {
                    "url": "https://quizizz.com/media/resource/gs/quizizz-media/questions/L2FwcGhvc3RpbmdfcHJvZC9ibG9icy9BRW5CMlVwajVWZnl0S2RBRXpIazROejFaSTl0dkU3Rmt6cjhtcTRvTGVxeFJzeHVLQzlZa3hzYjNZdkpNa3N1TTItaE5UNmVHUUZVdl9ZdTR6YnNaTk5hV0luZWhZQm9sUS5pOTBwLU1YLUtMRXR5YlBZ"
                  }
                ], //media
                "text": "Write an equation for this relationship.",
              }, //query
              "options": [
                {
                  "text": "y=1/5x"
                },
                {
                  "text": "y=1/2x"
                },
                {
                  "text": "y=2x"
                },
                {
                  "text": "y=5x"
                }
              ], //options
              "answer": 3
            }
          }
        ]
      }
    }

这是包含序列化类的代码,

import 'package:json_annotation/json_annotation.dart';
import 'questions_data/questions_quiz.dart';

part 'questions.g.dart';

@JsonSerializable(explicitToJson: true)
class CoreData {
  QuestionData data;

  CoreData({this.data});

  factory CoreData.fromJson(Map<String, dynamic> json) => _$CoreDataFromJson(json);
  Map<String, dynamic> toJson() => _$CoreDataToJson(this);
}

@JsonSerializable(explicitToJson: true)
class QuestionData {
  Quiz quiz;

  QuestionData({this.quiz});

  factory QuestionData.fromJson(Map<String, dynamic> json) => _$QuestionDataFromJson(json);
  Map<String, dynamic> toJson() => _$QuestionDataToJson(this);
}
@JsonSerializable(explicitToJson: true)
class QuestionsList {
  List<Questions> questions;

  QuestionsList({this.questions});

  factory QuestionsList.fromJson(Map<String, dynamic> json) => _$QuestionsListFromJson(json);
  Map<String, dynamic> toJson() => _$QuestionsListToJson(this);
}

@JsonSerializable(explicitToJson: true)
class Questions {
  Structure structure;

  Questions({this.structure});

  factory Questions.fromJson(Map<String, dynamic> json) => _$QuestionsFromJson(json);
  Map<String, dynamic> toJson() => _$QuestionsToJson(this);
}

@JsonSerializable(explicitToJson: true)
class Structure {
  String kind;
  Query query;
  Options options;
  int answer;

  Structure({this.kind, this.query, this.options, this.answer});

  factory Structure.fromJson(Map<String, dynamic> json) => _$StructureFromJson(json);
  Map<String, dynamic> toJson() => _$StructureToJson(this);
}
@JsonSerializable(explicitToJson: true)
class Quiz {
  String publishedVersion;
  @JsonKey(name: '_id')
  String id;
  Stats stats;
  CreatedBy createdBy;
  Info info;

  Quiz({this.publishedVersion, this.id, this.stats, this.createdBy, this.info});

  factory Quiz.fromJson(Map<String, dynamic> json) => _$QuizFromJson(json);
  Map<String, dynamic> toJson() => _$QuizToJson(this);
}

@JsonSerializable(explicitToJson: true)
class CreatedBy {
  Local local;
  String occupation;

  CreatedBy({this.local, this.occupation});

  factory CreatedBy.fromJson(Map<String, dynamic> json) => _$CreatedByFromJson(json);
  Map<String, dynamic> toJson() => _$CreatedByToJson(this);
}

@JsonSerializable(explicitToJson: true)
class Local {
  String username;

  Local({this.username});

  factory Local.fromJson(Map<String, dynamic> json) => _$LocalFromJson(json);
  Map<String, dynamic> toJson() => _$LocalToJson(this);
}

@JsonSerializable(explicitToJson: true)
class Stats {
  int played;
  int totalPlayers;

  Stats({this.played, this.totalPlayers});

  factory Stats.fromJson(Map<String, dynamic> json) => _$StatsFromJson(json);
  Map<String, dynamic> toJson() => _$StatsToJson(this);
}

@JsonSerializable(explicitToJson: true)
class Info {
  String name;
  String image;
  List<String> subjects, topics, subtopics;
  Questions questions;

  Info({
      this.name,
      this.image,
      this.subjects,
      this.topics,
      this.subtopics,
      this.questions});

  factory Info.fromJson(Map<String, dynamic> json) => _$InfoFromJson(json);
  Map<String, dynamic> toJson() => _$InfoToJson(this);
}
@JsonSerializable(explicitToJson: true)
class Query {
  String text;
  List<Images> media;

  Query({this.text, this.media});

  factory Query.fromJson(Map<String, dynamic> json) => _$QueryFromJson(json);
  Map<String, dynamic> toJson() => _$QueryToJson(this);
}

@JsonSerializable(explicitToJson: true)
class Images {
  String url;
  
  Images({this.url});

  factory Images.fromJson(Map<String, dynamic> json) => _$ImagesFromJson(json);
  Map<String, dynamic> toJson() => _$ImagesToJson(this);
}

@JsonSerializable(explicitToJson: true)
class Options {
  List<QuestionText> options;

  Options ({this.options});

  factory Options.fromJson(Map<String, dynamic> json) => _$OptionsFromJson(json);
  Map<String, dynamic> toJson() => _$OptionsToJson(this);
}

@JsonSerializable(explicitToJson: true)
class QuestionText {
  String text;

  QuestionText({this.text});

  factory QuestionText.fromJson(Map<String, dynamic> json) => _$QuestionTextFromJson(json);
  Map<String, dynamic> toJson() => _$QuestionTextToJson(this);
}

获取json文件并将其转换为dart的未来提供者,

import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
import 'package:quizizz_cheat/models/questions.dart';

    class QuestionsService {
      Future<CoreData> fetchQuestion() async {
        final response = await http.get(url);
        var jsonResponse = convert.jsonDecode(response.body);
        CoreData parsedQuestions = CoreData.fromJson(jsonResponse);
        
        return parsedQuestions;
      }
    }

这是基因编码,

part of 'questions.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

CoreData _$CoreDataFromJson(Map<String, dynamic> json) {
  return CoreData(
    data: json['data'] == null
        ? null
        : QuestionData.fromJson(json['data'] as Map<String, dynamic>),
  );
}

Map<String, dynamic> _$CoreDataToJson(CoreData instance) => <String, dynamic>{
      'data': instance.data?.toJson(),
    };

QuestionData _$QuestionDataFromJson(Map<String, dynamic> json) {
  return QuestionData(
    quiz: json['quiz'] == null
        ? null
        : Quiz.fromJson(json['quiz'] as Map<String, dynamic>),
  );
}

Map<String, dynamic> _$QuestionDataToJson(QuestionData instance) =>
    <String, dynamic>{
      'quiz': instance.quiz?.toJson(),
    };
QuestionsList _$QuestionsListFromJson(Map<String, dynamic> json) {
  return QuestionsList(
    questions: (json['questions'] as List)
        ?.map((e) =>
            e == null ? null : Questions.fromJson(e as Map<String, dynamic>))
        ?.toList(),
  );
}

Map<String, dynamic> _$QuestionsListToJson(QuestionsList instance) =>
    <String, dynamic>{
      'questions': instance.questions?.map((e) => e?.toJson())?.toList(),
    };

Questions _$QuestionsFromJson(Map<String, dynamic> json) {
  return Questions(
    structure: json['structure'] == null
        ? null
        : Structure.fromJson(json['structure'] as Map<String, dynamic>),
  );
}

Map<String, dynamic> _$QuestionsToJson(Questions instance) => <String, dynamic>{
      'structure': instance.structure?.toJson(),
    };

Structure _$StructureFromJson(Map<String, dynamic> json) {
  return Structure(
    kind: json['kind'] as String,
    query: json['query'] == null
        ? null
        : Query.fromJson(json['query'] as Map<String, dynamic>),
    options: json['options'] == null
        ? null
        : Options.fromJson(json['options'] as Map<String, dynamic>),
    answer: json['answer'] as int,
  );
}

Map<String, dynamic> _$StructureToJson(Structure instance) => <String, dynamic>{
      'kind': instance.kind,
      'query': instance.query?.toJson(),
      'options': instance.options?.toJson(),
      'answer': instance.answer,
    };
Quiz _$QuizFromJson(Map<String, dynamic> json) {
  return Quiz(
    publishedVersion: json['publishedVersion'] as String,
    id: json['_id'] as String,
    stats: json['stats'] == null
        ? null
        : Stats.fromJson(json['stats'] as Map<String, dynamic>),
    createdBy: json['createdBy'] == null
        ? null
        : CreatedBy.fromJson(json['createdBy'] as Map<String, dynamic>),
    info: json['info'] == null
        ? null
        : Info.fromJson(json['info'] as Map<String, dynamic>),
  );
}

Map<String, dynamic> _$QuizToJson(Quiz instance) => <String, dynamic>{
      'publishedVersion': instance.publishedVersion,
      '_id': instance.id,
      'stats': instance.stats?.toJson(),
      'createdBy': instance.createdBy?.toJson(),
      'info': instance.info?.toJson(),
    };

CreatedBy _$CreatedByFromJson(Map<String, dynamic> json) {
  return CreatedBy(
    local: json['local'] == null
        ? null
        : Local.fromJson(json['local'] as Map<String, dynamic>),
    occupation: json['occupation'] as String,
  );
}

Map<String, dynamic> _$CreatedByToJson(CreatedBy instance) => <String, dynamic>{
      'local': instance.local?.toJson(),
      'occupation': instance.occupation,
    };

Local _$LocalFromJson(Map<String, dynamic> json) {
  return Local(
    username: json['username'] as String,
  );
}

Map<String, dynamic> _$LocalToJson(Local instance) => <String, dynamic>{
      'username': instance.username,
    };

Stats _$StatsFromJson(Map<String, dynamic> json) {
  return Stats(
    played: json['played'] as int,
    totalPlayers: json['totalPlayers'] as int,
  );
}

Map<String, dynamic> _$StatsToJson(Stats instance) => <String, dynamic>{
      'played': instance.played,
      'totalPlayers': instance.totalPlayers,
    };

Info _$InfoFromJson(Map<String, dynamic> json) {
  return Info(
    name: json['name'] as String,
    image: json['image'] as String,
    subjects: (json['subjects'] as List)?.map((e) => e as String)?.toList(),
    topics: (json['topics'] as List)?.map((e) => e as String)?.toList(),
    subtopics: (json['subtopics'] as List)?.map((e) => e as String)?.toList(),
    questions: json['questions'] == null
        ? null
        : Questions.fromJson(json['questions'] as Map<String, dynamic>),
  );
}

Map<String, dynamic> _$InfoToJson(Info instance) => <String, dynamic>{
      'name': instance.name,
      'image': instance.image,
      'subjects': instance.subjects,
      'topics': instance.topics,
      'subtopics': instance.subtopics,
      'questions': instance.questions?.toJson(),
    };
Query _$QueryFromJson(Map<String, dynamic> json) {
  return Query(
    text: json['text'] as String,
    media: (json['media'] as List)
        ?.map((e) =>
            e == null ? null : Images.fromJson(e as Map<String, dynamic>))
        ?.toList(),
  );
}

Map<String, dynamic> _$QueryToJson(Query instance) => <String, dynamic>{
      'text': instance.text,
      'media': instance.media?.map((e) => e?.toJson())?.toList(),
    };

Images _$ImagesFromJson(Map<String, dynamic> json) {
  return Images(
    url: json['url'] as String,
  );
}

Map<String, dynamic> _$ImagesToJson(Images instance) => <String, dynamic>{
      'url': instance.url,
    };

Options _$OptionsFromJson(Map<String, dynamic> json) {
  return Options(
    options: (json['options'] as List)
        ?.map((e) =>
            e == null ? null : QuestionText.fromJson(e as Map<String, dynamic>))
        ?.toList(),
  );
}

Map<String, dynamic> _$OptionsToJson(Options instance) => <String, dynamic>{
      'options': instance.options?.map((e) => e?.toJson())?.toList(),
    };

QuestionText _$QuestionTextFromJson(Map<String, dynamic> json) {
  return QuestionText(
    text: json['text'] as String,
  );
}

Map<String, dynamic> _$QuestionTextToJson(QuestionText instance) =>
    <String, dynamic>{
      'text': instance.text,
    };

这是转换后的json文件显示的代码

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:quiz/screens/home.dart';
import 'package:quiz/services/questions_service.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final QuestionsService questionsService = QuestionsService();
  @override
  Widget build(BuildContext context) {
    return FutureProvider(
      create: (context) async => questionsService.fetchQuestion(),
      catchError: (context, error) {
        print(error.toString());
      },
          child: MaterialApp(
        title: 'Quizizz cheat',
        home: HomePage(),
      ),
    );
  }
}
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var question = Provider.of<CoreData>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Quizizz Cheat'),
      ),
      body: question == null
          ? Center(child: CircularProgressIndicator())
          : Center(
              child: Text(question.data.quiz.info.questions.structure.kind),
          ),
    );
  }
}

当我试着运行这个项目时,我遇到了这个错误

i/flutter(23347): type'List'不是type'Map的子类型

我相信问题来自这段代码,它试图转换包含映射列表的json和包含json序列化方法的代码

@JsonSerializable(explicitToJson: true)
    class QuestionsList {
      List<Questions> questions;
    
      QuestionsList({this.questions});
    
      factory QuestionsList.fromJson(Map<String, dynamic> json) => _$QuestionsListFromJson(json);
      Map<String, dynamic> toJson() => _$QuestionsListToJson(this);
    }

共有1个答案

喻珂
2023-03-14

我已经解决了这个问题,似乎在编写代码时需要更加小心。答案很简单,我需要改变这个类型。。。

@JsonSerializable(explicitToJson: true)
class Info {
  String name;
  String image;
  List<String> subjects, topics, subtopics;
  Questions questions;

  Info({
      this.name,
      this.image,
      this.subjects,
      this.topics,
      this.subtopics,
      this.questions});

  factory Info.fromJson(Map<String, dynamic> json) => _$InfoFromJson(json);
  Map<String, dynamic> toJson() => _$InfoToJson(this);
}

对此。。。

@JsonSerializable(explicitToJson: true)
class Info {
  String name;
  String image;
  List<String> subjects, topics, subtopics;
  List<Questions> questions;

  Info({
      this.name,
      this.image,
      this.subjects,
      this.topics,
      this.subtopics,
      this.questions});

  factory Info.fromJson(Map<String, dynamic> json) => _$InfoFromJson(json);
  Map<String, dynamic> toJson() => _$InfoToJson(this);
}

而从这个...

@JsonSerializable(explicitToJson: true)
class Structure {
  String kind;
  Query query;
  Options options;
  int answer;

  Structure({this.kind, this.query, this.options, this.answer});

  factory Structure.fromJson(Map<String, dynamic> json) => _$StructureFromJson(json);
  Map<String, dynamic> toJson() => _$StructureToJson(this);
}

对此。。。

@JsonSerializable(explicitToJson: true)
class Structure {
  String kind;
  Query query;
  List<QuestionText> options;
  int answer;

  Structure({this.kind, this.query, this.options, this.answer});

  factory Structure.fromJson(Map<String, dynamic> json) => _$StructureFromJson(json);
  Map<String, dynamic> toJson() => _$StructureToJson(this);
}
 类似资料:
  • 我对Flutter编程非常陌生,我正在尝试导入一个本地JSON文件,其中包含书籍数据,如标题、作者、发布年份等。 最初我使用JSON-to-DART转换器来组装一个图书数据模型,现在我正在尝试创建一个函数,在该函数中,程序获取本地JSON文件,并使用类中的方法将数据解析为地图。 我遇到的问题是返回类型

  • 我是一个新的颤振和得到类型错误。我正在尝试使用json自动序列化。 在做了一些调整后这里看起来是这样的 下面是我如何尝试从api获取数据 我的类如下所示 谁能帮我一下吗。我被困在这里了。我一直在尝试不同的方法,但都不管用。非常感谢。

  • 我试图创建动态下拉,其值是从使用微服务的查找表之一填充,但我已经尝试了许多方式相同,到目前为止,我还没有成功地使其工作。 下面的代码用于调用webservice 这是我的对象类型 仅用于显示目前运行的以下代码 我做了什么我尝试调用webservice在多种方式调用它,尝试铸造服务响应直接使用JSON字符串响应和可能的事情我尝试过。 你能在这里帮忙吗?我们将不胜感激。

  • 因此,我创建了一个应用程序,通过api读取数据,并尝试解析JSON api 这是我的错误截图 我试着把它改成一个列表,但它仍然读取一个错误 这是我的密码大象。飞奔 如何纠正此错误?请帮忙

  • 你好,我正在做一个api调用,在那里我得到了一系列的横幅。我正在犯错误- 横幅。飞奔 横幅。飞奔 api_base_助手。飞奔 得到你的横幅。飞奔

  • 我有一个问题,因为2小时。我有这个错误,我看到了更多的主题,但我不能解决它。 消息:_TypeError(类型列表不是类型映射的子类型)颤动 我的模型: 我的主题屏幕: 我尝试了更多的教程和不同的主题,但我有相同的错误。。。 非常感谢。