【问题标题】:Difficulties When Loading And Saving JSON Files加载和保存 JSON 文件时的困难
【发布时间】:2020-06-23 16:22:26
【问题描述】:

我想问一下下面的错误是什么意思以及如何解决它:

import 'dart:convert';
import './topic.dart';

class Subject {
  String name;
  bool isMajor;
  List<Topic> topics;

  Subject({this.name, this.isMajor, this.topics});

  factory Subject.fromJSON(Map<String, dynamic> json) {
    if (json != null) {
      return Subject(
          name: json['name'],
          isMajor: json['isMajor'],
          topics: List<Topic>.from(
              json['topics'].map((topic) => Topic.fromJSON(topic))));
    } else {
      return null;
    }
  }

  Map<String, dynamic> toJSON() {
    return {
      'name': name,
      'isMajor': isMajor,
      'topics': topics.map((topic) => jsonEncode(topic.toJSON())).toList(),
    };
  }
}

错误与这一行有关:json['topics'].map((topic) =&gt; Topic.fromJSON(topic))));

上面写着:_TypeError (type 'String' is not a subtype of type 'Map&lt;String, dynamic&gt;')

我认为[{ data: ... }]{ data: ... } 在某种程度上存在差异,但我不知道在哪里解决它!

也许你有最后的线索!

示例 JSON:

[
  {
    "name": "Amet do id ea velit",
    "isMajor": true,
    "topics": [
      {
        "name": "Elit exercitation excepteur",
        "contents": [
          {
            "title": "Ad id irure aute exercitation occaecat nostrud",
            "body": "Cupidatat nisi ad quis officia aliqua fugiat ullamco",
            "isImportant": false
          }
        ]
      }
    ]
  }
]

【问题讨论】:

标签: json flutter dart file-io


【解决方案1】:

使用这个模型类:

class Subject  {
  String name;
  bool isMajor;
  List<Topics> topics;

  Subject({this.name, this.isMajor, this.topics});

  Subject.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    isMajor = json['isMajor'];
    if (json['topics'] != null) {
      topics = new List<Topics>();
      json['topics'].forEach((v) {
        topics.add(new Topics.fromJson(v));
      });
    }
  }

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

class Topics {
  String name;
  List<Contents> contents;

  Topics({this.name, this.contents});

  Topics.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    if (json['contents'] != null) {
      contents = new List<Contents>();
      json['contents'].forEach((v) {
        contents.add(new Contents.fromJson(v));
      });
    }
  }

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

class Contents {
  String title;
  String body;
  bool isImportant;

  Contents({this.title, this.body, this.isImportant});

  Contents.fromJson(Map<String, dynamic> json) {
    title = json['title'];
    body = json['body'];
    isImportant = json['isImportant'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['title'] = this.title;
    data['body'] = this.body;
    data['isImportant'] = this.isImportant;
    return data;
  }
}

【讨论】:

    【解决方案2】:

    { data: ... } 这是您获得单个对象的地方

    [{ data: ... }] 这是您获取该对象列表的位置。

    如果您的帖子发布了模型类,只需编辑添加以下内容:

    1) 放入您的示例 JSON。

    2) 并仅显示出现错误的代码,否则将不胜感激。

    所以我所做的就是从你提供的 json 中创建一个示例:

    以下是您提供的示例 json:

    [
        {
          "name": "Amet do id ea velit",
          "isMajor": true,
          "topics": [
            {
              "name": "Elit exercitation excepteur",
              "contents": [
                {
                  "title": "Ad id irure aute exercitation occaecat nostrud",
                  "body": "Cupidatat nisi ad quis officia aliqua fugiat ullamco",
                  "isImportant": false
                }
              ]
            }
          ]
        }
      ]
    

    查看下面的模型类以获取您提供的 json

    // To parse this JSON data, do
    //
    //     final subject = subjectFromJson(jsonString);
    
    import 'dart:convert';
    
    List<Subject> subjectFromJson(String str) => List<Subject>.from(json.decode(str).map((x) => Subject.fromJson(x)));
    
    String subjectToJson(List<Subject> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
    
    class Subject {
        String name;
        bool isMajor;
        List<Topic> topics;
    
        Subject({
            this.name,
            this.isMajor,
            this.topics,
        });
    
        factory Subject.fromJson(Map<String, dynamic> json) => Subject(
            name: json["name"],
            isMajor: json["isMajor"],
            topics: List<Topic>.from(json["topics"].map((x) => Topic.fromJson(x))),
        );
    
        Map<String, dynamic> toJson() => {
            "name": name,
            "isMajor": isMajor,
            "topics": List<dynamic>.from(topics.map((x) => x.toJson())),
        };
    }
    
    class Topic {
        String name;
        List<Content> contents;
    
        Topic({
            this.name,
            this.contents,
        });
    
        factory Topic.fromJson(Map<String, dynamic> json) => Topic(
            name: json["name"],
            contents: List<Content>.from(json["contents"].map((x) => Content.fromJson(x))),
        );
    
        Map<String, dynamic> toJson() => {
            "name": name,
            "contents": List<dynamic>.from(contents.map((x) => x.toJson())),
        };
    }
    
    class Content {
        String title;
        String body;
        bool isImportant;
    
        Content({
            this.title,
            this.body,
            this.isImportant,
        });
    
        factory Content.fromJson(Map<String, dynamic> json) => Content(
            title: json["title"],
            body: json["body"],
            isImportant: json["isImportant"],
        );
    
        Map<String, dynamic> toJson() => {
            "title": title,
            "body": body,
            "isImportant": isImportant,
        };
    }
    
    

    只需查看以下代码:

    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:sample_project_for_api/model.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
    
      List<Subject> subjectList = List();
      List<Topic> topicList = List();
      List<Content> contentList = List();
    
      @override
      void initState() {
        super.initState();
        loadYourData();
      }
    
      loadYourData() async {
        String responseStr = await loadFromAssets();
        List<Subject> subject = subjectFromJson(responseStr);
        // here from above you complete subjects list
        for (int i = 0; i < subject.length; i++) {
          print(subject[i].isMajor.toString());
          print(subject[i].name);
          print(subject[i].topics.length);
          topicList = subject[i].topics;
          // here you get the topics list from above
          for (int j = 0; j < topicList.length; j++) {
            print(topicList[j].name);
    
            contentList = topicList[j].contents;
            // here you get the contents list
    
            for (int z = 0; z < contentList.length; z++) {
              print(contentList[z].body);
    
              print(contentList[z].isImportant.toString());
    
              print(contentList[z].title);
            }
          }
        }
      }
    
      Future<String> loadFromAssets() async {
        return await rootBundle.loadString('json/parse.json');
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          home: Scaffold(
            body: Center(
                child: Text('Random Text sample')),
          ),
        );
      }
    }
    
    

    【讨论】:

    • 抱歉,这并不能回答我的问题。
    • 因为你没有放主文件我不能准确的告诉你,如果解决了那就太好了
    【解决方案3】:

    问题是我不应该使用 jsonEncode

    它应该看起来完全一样:

      Map<String, dynamic> toJSON() {
        return {
          'name': name,
          'isMajor': isMajor,
          'topics': topics,
        };
      }
    

    【讨论】:

    • 这是问题的答案吗?你的问题到底是什么?类主题在哪里,你在哪里初始化它?请阅读如何在 Stackoverflow 上发布问题的规则!
    猜你喜欢
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 2012-03-10
    • 2018-01-19
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    相关资源
    最近更新 更多