从Json转换嵌套对象将返回null

从Json转换嵌套对象将返回null,json,flutter,object,dart,constructor,Json,Flutter,Object,Dart,Constructor,我有一个像这样的嵌套对象,只是稍微大一点: "name": "String", "exercise": [ { "index": 1, }

我有一个像这样的嵌套对象,只是稍微大一点:

"name": "String",       
    "exercise": [               
                   {                
                   "index": 1,                                  
                   }            
            ],              
    "pause": [              
        {"index":2},                        
    ]           
我将练习和暂停转换为Json字符串,并将它们保存在SQFLite的一列中

问题 当我读取数据时,一切正常,包括列表(非嵌套),但当我读取嵌套对象的值时,嵌套对象的两个列表都是空的,这会给出一个错误

item.exercise[0].index.toString()

Valid Value range is empty: 0
当我只读
item.exercise.toString()
时,它返回
[]
。没有
!=无效的[…]:List()
它还抛出一个错误

我从数据库中获取的数据(缩短) 名单:

[{name: number 1, id: 56, exercise: [{"index":1,"weightGoal":[15,16,17]}, {"index":3,"weightGoal":[15,16,17]}], pause: [{"index":2}]},{"index":4}]}]
我用它做什么 在这里,我尝试浏览列表并将其转换为PlanModel的列表:

List<PlanModel> list =
        res.isNotEmpty ? res.map((c) => PlanModel.fromJson(c)).toList() : [];
    return list;
列表=
res.isNotEmpty?res.map((c)=>PlanModel.fromJson(c)).toList():[];
退货清单;
全模型
PlanModel-planModelFromJson(String-str)=>PlanModel.fromJson(json.decode(str));
字符串planModelToJson(PlanModel数据)=>json.encode(data.toJson());
类平面模型{
平面模型({
这个名字,
这个身份证,
这几天,
这个,帕斯蒂德,
这件事已经完成了,
这个,这个演习,,
这个,暂停,
});
字符串名;
int-id;
列出工作日;
int-pastId;
int timestone;
列表练习;
列表暂停;
factory PlanModel.fromJson(映射json)=>PlanModel(
名称:json[“名称”],
id:json[“id”],
workoutDays:List.from(jsonDecode(json[“workoutDays”]),
pastId:json[“pastId”],
timesDone:json[“timesDone”],
exercise:json[“exercise”!=null?新列表。from(json[“exercise”].map((x)=>exercise.fromJson(x)):List(),
pause:json[“pause”]!=null?新列表。from(json[“pause”].map((x)=>pause.fromJson(x)):List(),
);
映射到JSON()=>{
“姓名”:姓名,
“id”:id,
“workoutDays”:列表.from(workoutDays.map((x)=>x)),
“帕斯蒂德”:帕斯蒂德,
“timesDone”:timesDone,
“Exercise”:List.from(Exercise.map((x)=>x.toJson()),
“Pause”:List.from(Pause.map((x)=>x.toJson()),
};
}
课堂练习{
练习({
这个索引,,
这个名字,
这个目标,,
这个目标,,
这个目标,,
这个时间目标,
这是我的目标,
});
整数指数;
字符串名;
国际目标;
勇敢的目标;
列出目标;
国际时间目标;
列出设定目标;
fromJson(动态json){
//在json中使用此[]包装的任何内容都将转换为列表
//用这个{}环绕的任何东西都是映射
index=json[“index”];
name=json[“name”];
goal=json[“goal”];
repGoal=json[“repGoal”];
weightGoal=json[“weightGoal”]!=null?json[“weightGoal”]。cast():[];
timeGoal=json[“timeGoal”];
setGoal=json[“setGoal”]!=null?json[“setGoal”].cast():[];
}
映射到JSON()=>{
“索引”:索引,
“姓名”:姓名,
“目标”:目标,
“repGoal”:repGoal,
“weightGoal”:List.from(weightGoal.map((x)=>x)),
“时间目标”:时间目标,
“setGoal”:List.from(setGoal.map((x)=>x)),
};
}
课堂停顿{
停顿({
这个索引,,
这个时间单位是米秒,
});
整数指数;
int timeInMilSec;
工厂暂停。fromJson(映射json)=>暂停(
索引:json[“索引”],
timeInMilSec:json[“timeInMilSec”],
);
映射到JSON()=>{
“索引”:索引,
“timeInMilSec”:timeInMilSec,
};
}
请先阅读此内容。

你需要稍微修改一下这段代码来为你工作,但想法是; 同时阅读代码中的注释

如果json字符串附带有
[]
周围的字符串,则json.decode会将其解码为
列表

如果它带有
{}
,这个json.decode将把它解码为
Map

注意:在json.decode上使用泛型时要小心,我建议不要这样做

jsonString
中的数据实际上与
fromJson
函数中的值不一致。您提供的json字符串不是很好。所以我想你会明白如何根据自己的需要来操作它

主构造函数
练习
也可用于初始数据

import 'dart:convert';
class Exercise{
  Exercise({this.index, 
            this.name, 
            this.repGoal, 
            this.weightGoal, 
            this.setGoal});
  
  String index;
  String name;
  String repGoal;
  String weightGoal;
  String setGoal;


Exercise.fromJson(dynamic json) : 
    // anything that is wrapped around with this [] in json is converted as list
    // anything that is wrapped around with this {} is map
    index = json["exercise"][0]["index"].toString(),
    name = json["name"].toString(),
    repGoal = json["repGoal"].toString(),
    weightGoal = json["weightGoal"].toString(),
    setGoal = json["setGoal"].toString();
  
  
}

void main(){
  String jsonString = '{name: number 1, id: 56, exercise: [{"index":1,"weightGoal":[15,16,17], pause: [{"index":2}]}';
  Map json = json.decode(jsonString);
  Exercise.fromJson(json);
  
}
我发现了:)

我已经将我的fromJson重新构造为这个,特别是jsonDecode非常重要,因为
json[“exercise”]
只是一个字符串

PlanModel.fromJson(dynamic json) {
    name = json["name"];
    if (json["exercise"] != null) {
      exercise = [];
      jsonDecode(json["exercise"]).forEach((v) {
        exercise.add(Exercise.fromJson(v));
      });
    }}
现在我可以使用

PlanModel item = snapshot.data[index];

item.exercise[0].timeGoal.toString()
    

我不确定,但我认为密钥是区分大小写的。您正在使用:json[“Exercise”]和json[“Pause”]@ClaudioCastro谢谢您的评论,但这很好,我也将它们都初始化为大写,因为没有变量,而是类。@M123您能给我们您得到的所有数据吗,PlanModel的完整版本,还有你的练习的完整版本,这样我就可以测试它,并让它发挥作用?@manofknowledge这里你的goexercise在数据库中是小写的,但是你尝试使用带有大写字母EThanks的练习来获得它,谢谢。我尝试了更多的方法并编辑了我的问题,但是我得到的练习列表是空的,这意味着,如果我试图从练习[0]中得到一个值,我会得到一个错误我真的为你感到高兴!对不起,我没能早点回答。@manofknowledge谢谢,没问题,我刚刚给了你奖金,因为你处理了这个问题,谢谢你
PlanModel item = snapshot.data[index];

item.exercise[0].timeGoal.toString()