Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
加载和保存JSON文件时遇到的困难_Json_Flutter_Dart_File Io - Fatal编程技术网

加载和保存JSON文件时遇到的困难

加载和保存JSON文件时遇到的困难,json,flutter,dart,file-io,Json,Flutter,Dart,File Io,我想问一下以下错误是什么意思以及如何修复它: 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>

我想问一下以下错误是什么意思以及如何修复它:

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(),
    };
  }
}
{数据:…}
这是获得单个对象的位置

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

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

1) 把你的样本放在JSON上

2) 只需显示代码中出现错误的位置,否则代码块会很受欢迎

因此,我所做的是根据您提供的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示例:

[
    {
      "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,
    };
}

//要解析此JSON数据,请执行以下操作
//
//最终主题=subjectFromJson(jsonString);
导入“dart:convert”;
List subjectFromJson(String str)=>List.from(json.decode(str.map)(x)=>Subject.fromJson(x));
字符串subjectToJson(List data)=>json.encode(List.from(data.map)((x)=>x.toJson());
班级科目{
字符串名;
布尔·伊斯马约尔;
列出主题;
主题({
这个名字,
这是伊斯马约尔,
这个,这个话题,,
});
factory Subject.fromJson(映射json)=>Subject(
名称:json[“名称”],
isMajor:json[“isMajor”],
topics:List.from(json[“topics”].map((x)=>Topic.fromJson(x)),
);
映射到JSON()=>{
“姓名”:姓名,
“isMajor”:isMajor,
“topics”:List.from(topics.map((x)=>x.toJson()),
};
}
课堂主题{
字符串名;
列出内容;
话题({
这个名字,
这个.内容,,
});
工厂主题.fromJson(映射json)=>Topic(
名称:json[“名称”],
contents:List.from(json[“contents”].map((x)=>Content.fromJson(x)),
);
映射到JSON()=>{
“姓名”:姓名,
“contents”:List.from(contents.map((x)=>x.toJson()),
};
}
课堂内容{
字符串标题;
弦体;
布尔是重要的;
内容({
这个名字,
这个,身体,,
这很重要,
});
工厂内容.fromJson(映射json)=>Content(
标题:json[“标题”],
body:json[“body”],
isImportant:json[“isImportant”],
);
映射到JSON()=>{
“头衔”:头衔,
“身体”:身体,
“重要”:重要,
};
}
只需查看以下代码:

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')),
      ),
    );
  }
}

导入“包装:颤振/材料.省道”;
导入“包:flifter/services.dart”;
导入“package:sample_project_for_api/model.dart”;
void main()=>runApp(MyApp());
类MyApp扩展了StatefulWidget{
@凌驾
_MyAppState createState()=>\u MyAppState();
}
类MyAppState扩展了状态{
List subjectList=List();
List topicList=List();
List contentList=List();
@凌驾
void initState(){
super.initState();
加载您的数据();
}
loadYourData()异步{
String responsest=await loadFromAssets();
List subject=subjectFromJson(responsest);
//在这里,您可以从上面填写科目列表
for(int i=0;i
问题是我不应该使用jsonecode

应该是这样的:

  Map<String, dynamic> toJSON() {
    return {
      'name': name,
      'isMajor': isMajor,
      'topics': topics,
    };
  }
Map to json(){
返回{
“名称”:名称,
“isMajor”:isMajor,
"话题":话题,,
};
}

使用此模型类:

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;
  }
}
课程主题{
字符串名;
布尔·伊斯马约尔;
列出主题;
主题({this.name,this.isMajor,this.topics});
Subject.fromJson(映射json){
name=json['name'];
isMajor=json['isMajor'];
if(json['topics']!=null){
主题=新列表();
json['topics'].forEach((v){
topics.add(newtopics.fromJson(v));
});
}
}
映射到JSON(){
最终地图数据=新地图();
数据['name']=this.name;
数据['isMajor']=this.isMajor;
if(this.topics!=null){
data['topics']=this.topics.map((v)=>v.toJson()).toList();
}
返回数据;
}
}
课堂主题{
字符串名;
列出内容;
主题({this.name,this.contents});
Topics.fromJson(映射json){
name=json['name'];
如果(json['contents']!=null){
contents=新列表();
json['contents'].forEach((v){
add(newcontents.fromJson(v));
});
}
}
映射到JSON(){
最终地图数据=新地图();
数据['name']=this.name;
如果(this.contents!=null){
data['contents']=this.contents.map((v)=>v.toJson()).toList();
}
返回数据;
}
}
课堂内容{
字符串标题;
弦体;
布尔是重要的;
内容({this.title,this.body,this.isImportant});
Contents.fromJson(映射json){
title=json['title'];
body=json['body'];
isImportant=json['isImportant'];
}
映射到JSON(){
最终地图数据=新地图();
数据['title']=this.title;
数据['body']=this.body;
数据['isImportant']=this.isImportant;
返回数据;
}
}

你的主题模型是什么?你看到了吗?你能在这里发布你的样本吗?你有:d抱歉,但这并不能回答我的问题。因为你没有放主文件,我无法准确地告诉你