【问题标题】:How to fetch json data and separate it based on a Parameter?如何获取 json 数据并根据参数将其分离?
【发布时间】:2020-01-28 04:51:18
【问题描述】:

我这里有一个 json 对象 -

{
    "error": "0",
    "message": "Got it!",
    "data": [
        {
            "status": false,
            "_id": "5e2fbb74d465702288c54038",
            "group_id": "5e0d9e993944e46ed9a86d95",
            "date": "2020-01-28T00:00:00.000Z",
            "title": "cciigcigc",
            "priority": 3,
            "description": "",
            "tasks": [],
            "created_date": "2020-01-28T04:41:24.576Z",
            "__v": 0
        }
    ]
}

我想根据 ["data"]["status"] 参数获取它;如果状态为假,则返回一个单独的列表,如果状态为真,则返回另一个列表。我试图以这种方式修改我当前的 fetch 方法 -

Future<List<Post>> gettask(bool identifier) async { // the identifier can be set to true and false 
  List<Post> statusComplete;
  List<Post> statusInComplete;

  String link = baseURL + fetchTodoByDate;
//  print("printing from get task = $setter");
  Stopwatch stopwatchbefore = new Stopwatch()..start();


  var res = await http.post(Uri.encodeFull(link), headers: {"Accept": "application/json", }, body: {"date" : setter.toString()});

  print('fetch executed in ${stopwatchbefore.elapsed}');


  if (res.statusCode == 200) {
    Stopwatch stopwatchafter = new Stopwatch()
      ..start();

    var data = json.decode(res.body);
    var rest = data["data"] as List;
    if(identifier == true){
      statusComplete = rest.map<Post>((json) {
        // need help in implementing logic here

        return Post.fromJson(json);
      }).toList();

      return statusComplete;

    }else if(identifier == false){
      statusInComplete = rest.map<Post>((json) {
        // need help in implementing logic here

        return Post.fromJson(json);
      }).toList();
      return statusInComplete;
    }

    print('statuscode executed in ${stopwatchafter.elapsed}');
    Future.delayed(Duration(seconds: 5));
  }


//  print("List Size: ${list.length}");
}

这是我第一次尝试以这种方式获取和分离数据。我试图看一些教程,但似乎没有一个能满足我的情况。

我能得到一些关于如何获取数据然后根据参数将其分开的建议吗?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    查看下面的示例,它将给出流程如何工作的基本概念。

    import 'package:flutter/material.dart';
    import 'dart:async';
    import 'package:flutter/services.dart';
    import 'package:json_parsing/models.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      List<Datum> dataList = List();
      bool _isLoading = false;
    
    
      Future<String> loadFromAssets() async {
        return await rootBundle.loadString('json/parse.json');
      }
    
      Future loadyourData() async {
        setState(() {
          _isLoading = true;
        });
    
    // this is the local json that i have loaded from the assets folder
    // you can make the http call here and else everything later is the same.
    
        String jsonString = await loadFromAssets();
        final yourData = dataFromJson(jsonString);
    
        dataList = yourData.data;
    
      var statusComplete = dataList.where((i) => i.status == true).toList();
    
        for (int i = 0; i < statusComplete.length; i++) {
          print('This is the list for true status :${statusComplete[i].title}');
        }
    
        var statusInComplete = dataList.where((i) => i.status == false).toList();
        print(statusInComplete[0].title);
    
    
    
    
        setState(() {
          _isLoading = false;
        });
      }
    
      @override
      void initState() {
        super.initState();
    
        loadyourData();
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          home: Scaffold(
              body: Container(
            child: _isLoading
                ? CircularProgressIndicator()
                : new ListView.builder(
                    itemCount: dataList.length,
                    itemBuilder: (BuildContext ctxt, int index) {
                      return new Text(dataList[index].status.toString());
                    }),
          )),
        );
      }
    }
    
    

    下面是模型类

    // To parse this JSON data, do
    //
    //     final data = dataFromJson(jsonString);
    
    import 'dart:convert';
    
    Data dataFromJson(String str) => Data.fromJson(json.decode(str));
    
    String dataToJson(Data data) => json.encode(data.toJson());
    
    class Data {
        String error;
        String message;
        List<Datum> data;
    
        Data({
            this.error,
            this.message,
            this.data,
        });
    
        factory Data.fromJson(Map<String, dynamic> json) => Data(
            error: json["error"],
            message: json["message"],
            data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
        );
    
        Map<String, dynamic> toJson() => {
            "error": error,
            "message": message,
            "data": List<dynamic>.from(data.map((x) => x.toJson())),
        };
    }
    
    class Datum {
        bool status;
        String id;
        String groupId;
        DateTime date;
        String title;
        int priority;
        String description;
        List<dynamic> tasks;
        DateTime createdDate;
        int v;
    
        Datum({
            this.status,
            this.id,
            this.groupId,
            this.date,
            this.title,
            this.priority,
            this.description,
            this.tasks,
            this.createdDate,
            this.v,
        });
    
        factory Datum.fromJson(Map<String, dynamic> json) => Datum(
            status: json["status"],
            id: json["_id"],
            groupId: json["group_id"],
            date: DateTime.parse(json["date"]),
            title: json["title"],
            priority: json["priority"],
            description: json["description"],
            tasks: List<dynamic>.from(json["tasks"].map((x) => x)),
            createdDate: DateTime.parse(json["created_date"]),
            v: json["__v"],
        );
    
        Map<String, dynamic> toJson() => {
            "status": status,
            "_id": id,
            "group_id": groupId,
            "date": date.toIso8601String(),
            "title": title,
            "priority": priority,
            "description": description,
            "tasks": List<dynamic>.from(tasks.map((x) => x)),
            "created_date": createdDate.toIso8601String(),
            "__v": v,
        };
    }
    
    

    这是你指定的 json

    {
        "error": "0",
        "message": "Got it!",
        "data": [
            {
                "status": false,
                "_id": "5e2fbb74d465702288c54038",
                "group_id": "5e0d9e993944e46ed9a86d95",
                "date": "2020-01-28T00:00:00.000Z",
                "title": "first",
                "priority": 3,
                "description": "",
                "tasks": [],
                "created_date": "2020-01-28T04:41:24.576Z",
                "__v": 0
            },
            {
                "status": true,
                "_id": "5e2fbb74d465702288c54038",
                "group_id": "5e0d9e993944e46ed9a86d95",
                "date": "2020-01-28T00:00:00.000Z",
                "title": "second",
                "priority": 3,
                "description": "",
                "tasks": [],
                "created_date": "2020-01-28T04:41:24.576Z",
                "__v": 0
            },
            {
                "status": true,
                "_id": "5e2fbb74d465702288c54038",
                "group_id": "5e0d9e993944e46ed9a86d95",
                "date": "2020-01-28T00:00:00.000Z",
                "title": "third",
                "priority": 3,
                "description": "",
                "tasks": [],
                "created_date": "2020-01-28T04:41:24.576Z",
                "__v": 0
            }
        ]
    }
    

    【讨论】:

    • 我想你误会了;我想用 status == false 获取所有 json 对象并返回一个列表(单独的列表),如果状态为 true,则返回另一个列表。无论状态参数如何,我在问题中提供的方法都会获取所有对象。请尝试修改问题中给定的方法。
    • 查看我所做的更改,也许这会解决您的问题
    • 我只需要在var statusInComplete = dataList.where((i) =&gt; i.status == false).toList(); 中,我将它设置为getTask() 方法并且它有效。谢谢你帮忙。祝你有美好的一天!
    【解决方案2】:

    试试这个模型类

    import 'dart:convert';
    
    Jsonmodel jsonmodelFromJson(String str) => Jsonmodel.fromJson(json.decode(str));
    
    String jsonmodelToJson(Jsonmodel data) => json.encode(data.toJson());
    
    class Jsonmodel {
        String error;
        String message;
        List<Datum> data;
    
        Jsonmodel({
            this.error,
            this.message,
            this.data,
        });
    
        factory Jsonmodel.fromJson(Map<String, dynamic> json) => Jsonmodel(
            error: json["error"],
            message: json["message"],
            data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
        );
    
        Map<String, dynamic> toJson() => {
            "error": error,
            "message": message,
            "data": List<dynamic>.from(data.map((x) => x.toJson())),
        };
    }
    
    class Datum {
        bool status;
        String id;
        String groupId;
        DateTime date;
        String title;
        int priority;
        String description;
        List<dynamic> tasks;
        DateTime createdDate;
        int v;
    
        Datum({
            this.status,
            this.id,
            this.groupId,
            this.date,
            this.title,
            this.priority,
            this.description,
            this.tasks,
            this.createdDate,
            this.v,
        });
    
        factory Datum.fromJson(Map<String, dynamic> json) => Datum(
            status: json["status"],
            id: json["_id"],
            groupId: json["group_id"],
            date: DateTime.parse(json["date"]),
            title: json["title"],
            priority: json["priority"],
            description: json["description"],
            tasks: List<dynamic>.from(json["tasks"].map((x) => x)),
            createdDate: DateTime.parse(json["created_date"]),
            v: json["__v"],
        );
    
        Map<String, dynamic> toJson() => {
            "status": status,
            "_id": id,
            "group_id": groupId,
            "date": date.toIso8601String(),
            "title": title,
            "priority": priority,
            "description": description,
            "tasks": List<dynamic>.from(tasks.map((x) => x)),
            "created_date": createdDate.toIso8601String(),
            "__v": v,
        };
    }
    

    这样使用

    var res = await http.post(Uri.encodeFull(link), headers: {"Accept": 
     "application/json", }, body: {"date" : setter.toString()});
    
        Jsonmodel modeldata = jsonmodelFromJson(res);
        // do your stuff
        modeldata.data.foreach((data){
            if(data.status){
              //do your stuff
            }else{
              //do your stuff
            }
        });
    

    【讨论】:

    • 这不能回答问题。如何获取数据,然后在状态为 false 时返回单独的列表,反之亦然?
    • @simon_the_cat 你可以通过foreach查看状态,查看我更新的答案
    猜你喜欢
    • 2019-07-07
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 2014-08-27
    • 2021-03-25
    • 2013-01-19
    • 1970-01-01
    相关资源
    最近更新 更多