【问题标题】:Which of these is best to handle json Array? List<dynamic>or Map<String, dynamic>其中哪一个最适合处理 json 数组?列表<动态>或地图<字符串,动态>
【发布时间】:2021-12-11 21:31:22
【问题描述】:

我想从这个 json 响应中提取数据作为分组(结果、情感、心理运动和其他)从 api 中提取,但我对如何处理它感到困惑。 如果没有分组我可以完美处理,但分组时我迷路了。

{
    "result": [{
        "subject": "AGRICULTURE SCIENCE",
        "ca1": "21",
        "ex1": "60",
        "t1total": 81,
        "ca2": "21",
        "ex2": "53",
        "t2total": 74,
        "ca3": "28",
        "ex3": "60",
        "t3total": 88,
        "overalltotal": 243,
        "avr": 81
    }, {
        "subject": "BASIC SCIENCE",
        "ca1": "27",
        "ex1": "49",
        "t1total": 76,
        "ca2": "22",
        "ex2": "29",
        "t2total": 51,
        "ca3": "17",
        "ex3": "41",
        "t3total": 58,
        "overalltotal": 185,
        "avr": 61.67
    }, {
        "subject": "BASIC TECHNOLOGY",
        "ca1": "30",
        "ex1": "66",
        "t1total": 96,
        "ca2": "27",
        "ex2": "62",
        "t2total": 89,
        "ca3": "22",
        "ex3": "26",
        "t3total": 48,
        "overalltotal": 233,
        "avr": 77.67
    },],
    "others": {
        "pricomment": "He is a  good boy",
        "tcomment": "He is a gentle boy",
        "term1total": 1308,
        "term2total": 1315,
        "term3total": 1212,
        "overalltotal": 3835,
        "overallavr": 75.19607843137254,
        "test1total": "404",
        "test12total": "406",
        "test13total": "400",
        "exam1total": "904",
        "exam2total": "909",
        "exam3total": "812"
    },
    "affective": {
        "col1": "-",
        "col2": "-",
        "col3": "-",
        "col4": "-",
        "col5": "-",
        "col6": "-",
        "col7": "-",
        "col8": "-"
    },
    "psychomotor": {
        "col1": "-",
        "col2": "-",
        "col3": "-",
        "col4": "-"
    }
}

我试过这样做

void getTerm1Result() async {
    final response = await http.post(
      Uri.parse(TERM1 + sid + '&sess=' + sess + '&term=' + term),
      headers: {"Content-Type": "application/json"},
    );
    if (response.statusCode == 200) {
      print("reached");
      //Map<List, dynamic> resposne = jsonDecode(response.body);
      setState(() {
        result1 = [] as Map;
        
        result1 = jsonDecode(response.body);
        resultLoading = false;
//here Im trying to extract the name of the subject in the json which is my problem
print(result1['result'][0]['subject']);
      });
    } else {
      print("Not reached");
    }
  }

如何在颤振中提取? 我需要使用 List 还是 Map 当我使用 List 我得到 List is not a subtype of type Map 我会很感激你的回复。 谢谢

【问题讨论】:

  • 你能发布你想要得到的最终结果吗?你的代码显示了你到目前为止的尝试?
  • @Andrija 我已经更新了我的问题以包括我尝试过的内容

标签: flutter


【解决方案1】:

第 1 步:简化您的任务。创建一个为您工作的类。让我们说 data_model.dart 如下所示:

import 'dart:convert';

Data dataFromJson(String str) => Data.fromJson(json.decode(str));

String dataToJson(Data data) => json.encode(data.toJson());

class Data {
    Data({
        this.result,
        this.others,
        this.affective,
        this.psychomotor,
    });

    List<Result> result;
    Others others;
    Affective affective;
    Psychomotor psychomotor;

    factory Data.fromJson(Map<String, dynamic> json) => Data(
        result: List<Result>.from(json["result"].map((x) => Result.fromJson(x))),
        others: Others.fromJson(json["others"]),
        affective: Affective.fromJson(json["affective"]),
        psychomotor: Psychomotor.fromJson(json["psychomotor"]),
    );

    Map<String, dynamic> toJson() => {
        "result": List<dynamic>.from(result.map((x) => x.toJson())),
        "others": others.toJson(),
        "affective": affective.toJson(),
        "psychomotor": psychomotor.toJson(),
    };
}

class Affective {
    Affective({
        this.col1,
        this.col2,
        this.col3,
        this.col4,
        this.col5,
        this.col6,
        this.col7,
        this.col8,
    });

    String col1;
    String col2;
    String col3;
    String col4;
    String col5;
    String col6;
    String col7;
    String col8;

    factory Affective.fromJson(Map<String, dynamic> json) => Affective(
        col1: json["col1"],
        col2: json["col2"],
        col3: json["col3"],
        col4: json["col4"],
        col5: json["col5"],
        col6: json["col6"],
        col7: json["col7"],
        col8: json["col8"],
    );

    Map<String, dynamic> toJson() => {
        "col1": col1,
        "col2": col2,
        "col3": col3,
        "col4": col4,
        "col5": col5,
        "col6": col6,
        "col7": col7,
        "col8": col8,
    };
}

class Others {
    Others({
        this.pricomment,
        this.tcomment,
        this.term1Total,
        this.term2Total,
        this.term3Total,
        this.overalltotal,
        this.overallavr,
        this.test1Total,
        this.test12Total,
        this.test13Total,
        this.exam1Total,
        this.exam2Total,
        this.exam3Total,
    });

    String pricomment;
    String tcomment;
    int term1Total;
    int term2Total;
    int term3Total;
    int overalltotal;
    double overallavr;
    String test1Total;
    String test12Total;
    String test13Total;
    String exam1Total;
    String exam2Total;
    String exam3Total;

    factory Others.fromJson(Map<String, dynamic> json) => Others(
        pricomment: json["pricomment"],
        tcomment: json["tcomment"],
        term1Total: json["term1total"],
        term2Total: json["term2total"],
        term3Total: json["term3total"],
        overalltotal: json["overalltotal"],
        overallavr: json["overallavr"].toDouble(),
        test1Total: json["test1total"],
        test12Total: json["test12total"],
        test13Total: json["test13total"],
        exam1Total: json["exam1total"],
        exam2Total: json["exam2total"],
        exam3Total: json["exam3total"],
    );

    Map<String, dynamic> toJson() => {
        "pricomment": pricomment,
        "tcomment": tcomment,
        "term1total": term1Total,
        "term2total": term2Total,
        "term3total": term3Total,
        "overalltotal": overalltotal,
        "overallavr": overallavr,
        "test1total": test1Total,
        "test12total": test12Total,
        "test13total": test13Total,
        "exam1total": exam1Total,
        "exam2total": exam2Total,
        "exam3total": exam3Total,
    };
}

class Psychomotor {
    Psychomotor({
        this.col1,
        this.col2,
        this.col3,
        this.col4,
    });

    String col1;
    String col2;
    String col3;
    String col4;

    factory Psychomotor.fromJson(Map<String, dynamic> json) => Psychomotor(
        col1: json["col1"],
        col2: json["col2"],
        col3: json["col3"],
        col4: json["col4"],
    );

    Map<String, dynamic> toJson() => {
        "col1": col1,
        "col2": col2,
        "col3": col3,
        "col4": col4,
    };
}

class Result {
    Result({
        this.subject,
        this.ca1,
        this.ex1,
        this.t1Total,
        this.ca2,
        this.ex2,
        this.t2Total,
        this.ca3,
        this.ex3,
        this.t3Total,
        this.overalltotal,
        this.avr,
    });

    String subject;
    String ca1;
    String ex1;
    int t1Total;
    String ca2;
    String ex2;
    int t2Total;
    String ca3;
    String ex3;
    int t3Total;
    int overalltotal;
    double avr;

    factory Result.fromJson(Map<String, dynamic> json) => Result(
        subject: json["subject"],
        ca1: json["ca1"],
        ex1: json["ex1"],
        t1Total: json["t1total"],
        ca2: json["ca2"],
        ex2: json["ex2"],
        t2Total: json["t2total"],
        ca3: json["ca3"],
        ex3: json["ex3"],
        t3Total: json["t3total"],
        overalltotal: json["overalltotal"],
        avr: json["avr"].toDouble(),
    );

    Map<String, dynamic> toJson() => {
        "subject": subject,
        "ca1": ca1,
        "ex1": ex1,
        "t1total": t1Total,
        "ca2": ca2,
        "ex2": ex2,
        "t2total": t2Total,
        "ca3": ca3,
        "ex3": ex3,
        "t3total": t3Total,
        "overalltotal": overalltotal,
        "avr": avr,
    };
}

我将其命名为数据。

第 2 步。创建一个 Data 类的对象,让我们将其视为: Data? resultData;

第 3 步。使用此对象存储 API 响应:

void getTerm1Result() async {
    final response = await http.post(
      Uri.parse(TERM1 + sid + '&sess=' + sess + '&term=' + term),
      headers: {"Content-Type": "application/json"},
    );
    if (response.statusCode == 200) {
       Data? resultData;
     //this object has your data. 
       resultData = dataFromJson(response.body);  
    
     //You can use it anywhere 
     //to access list of result : use resultData.result
     //to access others: use resultData.others            
      //Map<List, dynamic> resposne = jsonDecode(response.body);
      setState(() {
        result1 = [] as Map;
        
        result1 = jsonDecode(response.body);
        resultLoading = false;
//here Im trying to extract the name of the subject in the json which is my problem
print(result1['result'][0]['subject']);
      });
    } else {
      print("Not reached");
    }
  }

注意:由于我不知道您如何使用变量,我将 resultData 保留为本地变量。您可以根据需要使用它。它基本上做的是我有一个对象映射,所以我将这些对象映射到一个类中。一个对象是对象列表,所以我获取了每个元素并制作了一个对象列表,您可以在工厂方法中看到它。

要轻松创建和处理数据,您可以使用https://app.quicktype.io/ 从 json 生成此类模型。

【讨论】:

  • 嗨,兄弟,我无法想象你会花这么多时间来帮助我。我真的很尊重你。非常感谢。总而言之,它按照您的建议工作。谢谢
  • 欢迎,永远。您可能会在 null 安全性方面遇到一些麻烦。如果你这样做,我会更新我的答案。
  • Bhanushli,哇,我再次试用链接。效果很好。尊重兄弟!
  • Bhanushli,哇,我再次试用链接。效果很好。尊重兄弟!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
  • 2017-08-27
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
相关资源
最近更新 更多