簡體   English   中英

Flutter 從 Json 轉換嵌套對象返回 null

[英]Flutter converting Nested Object from Json returns null

我有一個像這樣的嵌套對象,只是有點大:

"name": "String",       
    "exercise": [               
                   {                
                   "index": 1,                                  
                   }            
            ],              
    "pause": [              
        {"index":2},                        
    ]           

我將練習和暫停轉換為 Json 字符串,並將它們保存在 SQFLite 的列中。

問題

當我讀取數據時,一切正常,包括列表(非嵌套),但是當我讀取嵌套對象的值時,嵌套對象的兩個列表都是空的,它給出了錯誤。

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

Valid Value range is empty: 0

當我只閱讀item.exercise.toString()它返回[] 沒有!= null ? [...] : List<Exercise>() != null ? [...] : List<Exercise>()它也會拋出錯誤

我從我的數據庫中獲得的數據(已縮短)

清單:

[{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;

全型號

PlanModel planModelFromJson(String str) => PlanModel.fromJson(json.decode(str));

String planModelToJson(PlanModel data) => json.encode(data.toJson());

class PlanModel {
  PlanModel({
    this.name,
    this.id,
    this.workoutDays,
    this.pastId,
    this.timesDone,
    this.exercise,
    this.pause,
  });

  String name;
  int id;
  List<String> workoutDays;
  int pastId;
  int timesDone;
  List<Exercise> exercise;
  List<Pause> pause;

  factory PlanModel.fromJson(Map<String, dynamic> json) => PlanModel(
    name: json["name"],
    id: json["id"],
    workoutDays: List<String>.from(jsonDecode(json["workoutDays"])),
    pastId: json["pastId"],
    timesDone: json["timesDone"],
    exercise: json["Exercise"] != null ? new List<Exercise>.from(json["Exercise"].map((x) => Exercise.fromJson(x))): List<Exercise>(),
    pause: json["Pause"] != null ? new List<Pause>.from(json["Pause"].map((x) => Pause.fromJson(x))): List<Pause>(),
  );

  Map<String, dynamic> toJson() => {
    "name": name,
    "id": id,
    "workoutDays": List<dynamic>.from(workoutDays.map((x) => x)),
    "pastId": pastId,
    "timesDone": timesDone,
    "Exercise": List<dynamic>.from(exercise.map((x) => x.toJson())),
    "Pause": List<dynamic>.from(pause.map((x) => x.toJson())),
  };



}

class Exercise {
  Exercise({
    this.index,
    this.name,
    this.goal,
    this.repGoal,
    this.weightGoal,
    this.timeGoal,
    this.setGoal,
  });

  int index;
  String name;
  int goal;
  int repGoal;
  List<int> weightGoal;
  int timeGoal;
  List<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["index"];
    name = json["name"];
    goal = json["goal"];
    repGoal = json["repGoal"];
    weightGoal = json["weightGoal"] != null ? json["weightGoal"].cast<int>() : [];
    timeGoal = json["timeGoal"];
    setGoal = json["setGoal"] != null ? json["setGoal"].cast<String>() : [];
  }

  Map<String, dynamic> toJson() => {
    "index": index,
    "name": name,
    "goal": goal,
    "repGoal": repGoal,
    "weightGoal": List<dynamic>.from(weightGoal.map((x) => x)),
    "timeGoal": timeGoal,
    "setGoal": List<dynamic>.from(setGoal.map((x) => x)),
  };
}

class Pause {
  Pause({
    this.index,
    this.timeInMilSec,
  });

  int index;
  int timeInMilSec;

  factory Pause.fromJson(Map<String, dynamic> json) => Pause(
    index: json["index"],
    timeInMilSec: json["timeInMilSec"],
  );

  Map<String, dynamic> toJson() => {
    "index": index,
    "timeInMilSec": timeInMilSec,
  };
}

請先閱讀此內容。

你需要稍微修改一下這段代碼才能為你工作,但這個想法是這樣的; 還閱讀代碼中的注釋。

如果 json 字符串帶有[]周圍的字符串,則 json.decode 會將其解碼為List<Map>

如果它帶有{}則 json.decode 會將其解碼為Map

注意:在 json.decode 上使用泛型時要小心,我建議不要這樣做。

jsonString中的數據與fromJson函數中的值並不真正對應。 您提供的 json 字符串並不是很好。 所以我想你會明白如何根據你的需要操縱它。

還可以用於初始數據的主構造函數Exercise

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()
    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM