【问题标题】:Json parsing in dart (flutter)飞镖中的Json解析(颤振)
【发布时间】:2023-03-05 23:06:02
【问题描述】:

我是 Flutter 新手,对复杂的 json 解析不太了解。我查阅了几篇在线文章,但没有找到任何合适的解决方案。我的json如下

{
    "EmployeeName":"EmployeeName",
    "Incidents" : [
        {
            "Id":"1",
            "Text":"Text",
            "Photos":[
                {
                    "PhotoUrl" : "http://myphoto.com"
                },
                {
                    "PhotoUrl" : "http://myphoto.com"
                }
            ],
            "Notes" : [
                {
                    "Note":"Note"
                },
                {
                    "Note":"Note"
                }
            ]
        }
    ]
}

任何帮助都会很棒。

【问题讨论】:

  • 这能回答你的问题吗? Parsing Json in flutter
  • 我看过那个例子,但在我的例子中,我在数组中有数组。我在解析对象时遇到了困难。
  • @KirillMatrosov,感谢您的评论。我认为它会起作用。让我实现:)

标签: json flutter dart


【解决方案1】:

这是您的 json 的代码示例:

员工

class Employee{

String employeeName;
List<Incident> incidents;

Employee({this.employeeName, this.incidents});

Employee.fromJson(Map<String, dynamic> json) {
    employeeName = json['employeeName'];
    if (json['incidents'] != null) {
        incidents = new List<Incident>();
        json['incidents'].forEach((v) {
            incidents.add(new Incident.fromJson(v));
        });
    }
}

Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.employeeName != null) data['employeeName'] = this.employeeName;
    if (this.incidents != null) {
        data['incidents'] = this.incidents.map((v) => v.toJson()).toList();
    }
    return data;
}
}

事件

class Incident{

String id;
String text;
List<Photo> photos;
List<Note> notes;

Incident({this.id, this.text, this.photos, this.notes});

Incident.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    text = json['text'];
    if (json['photos'] != null) {
        photos = new List<Photo>();
        json['photos'].forEach((v) {
            photos.add(new Photo.fromJson(v));
        });
    }
    if (json['notes'] != null) {
        notes = new List<Note>();
        json['notes'].forEach((v) {
            notes.add(new Note.fromJson(v));
        });
    }
}

Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.id != null) data['id'] = this.id;
    if (this.text != null) data['text'] = this.text;
    if (this.photos != null) {
        data['photos'] = this.photos.map((v) => v.toJson()).toList();
    }
    if (this.notes != null) {
        data['notes'] = this.notes.map((v) => v.toJson()).toList();
    }
    return data;
}
}

注意

class Note{

String note;

Note({this.note});

Note.fromJson(Map<String, dynamic> json) {
    note = json['note'];
}

Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.note != null) data['note'] = this.note;
    return data;
}
}

照片

class Photo{

String photoUrl;

Photo({this.photoUrl});

Photo.fromJson(Map<String, dynamic> json) {
    photoUrl = json['photoUrl'];
}

Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.photoUrl != null) data['photoUrl'] = this.photoUrl;
    return data;
}
}

【讨论】:

    【解决方案2】:
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:sample_project_for_api/Employee.dart';
    
    main() => runApp(MyApp());
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      bool _isLoading = false;
    
      List<Employee> emp = new List();
      @override
      void initState() {
        super.initState();
        getEmployeeDetails();
      }
    
      Future<String> loadPersonFromAssets() async {
        return await rootBundle.loadString('json/parse.json');
      }
    
      getEmployeeDetails() async {
        setState(() {
          _isLoading = true;
        });
    
        String jsonString = await loadPersonFromAssets();
        final employee = employeeFromJson(jsonString);
        emp.add(employee);
        print('This is the employee name : ${employee.employeeName}');
        for (int i = 0; i < employee.incidents.length; i++) {
          print('This is the employee id ${employee.incidents[i].id}');
          print('This is the employee text ${employee.incidents[i].text}');
        }
        for (int i = 0; i < employee.incidents.length; i++) {
          for (int j = 0; j < employee.incidents[i].notes.length; j++) {
            print('This are the notes : ${employee.incidents[i].notes[j].note}');
          }
        }
        setState(() {
          _isLoading = false;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
          body: _isLoading == true
              ? CircularProgressIndicator()
              : Container(
                  child: ListView.builder(
                    itemCount: emp.length,
                    itemBuilder: (context, i) {
    
                      return Card(
                        child: Column(
                          children: <Widget>[
                            Text(emp[i].employeeName),
                            Text(emp[i].incidents[0].id),
                            Text(emp[i].incidents[0].notes[0].note),
                          ],
                        ),
                      );
                    },
                  ),
                ),
        ));
      }
    }
    
    
    

    查看你要解析的 JSON,我已经给你简单的逻辑,看你如何解析。

    
    
    import 'dart:convert';
    
    Employee employeeFromJson(String str) => Employee.fromJson(json.decode(str));
    
    String employeeToJson(Employee data) => json.encode(data.toJson());
    
    class Employee {
        String employeeName;
        List<Incident> incidents;
    
        Employee({
            this.employeeName,
            this.incidents,
        });
    
        factory Employee.fromJson(Map<String, dynamic> json) => Employee(
            employeeName: json["EmployeeName"],
            incidents: List<Incident>.from(json["Incidents"].map((x) => Incident.fromJson(x))),
        );
    
        Map<String, dynamic> toJson() => {
            "EmployeeName": employeeName,
            "Incidents": List<dynamic>.from(incidents.map((x) => x.toJson())),
        };
    }
    
    class Incident {
        String id;
        String text;
        List<Photo> photos;
        List<Note> notes;
    
        Incident({
            this.id,
            this.text,
            this.photos,
            this.notes,
        });
    
        factory Incident.fromJson(Map<String, dynamic> json) => Incident(
            id: json["Id"],
            text: json["Text"],
            photos: List<Photo>.from(json["Photos"].map((x) => Photo.fromJson(x))),
            notes: List<Note>.from(json["Notes"].map((x) => Note.fromJson(x))),
        );
    
        Map<String, dynamic> toJson() => {
            "Id": id,
            "Text": text,
            "Photos": List<dynamic>.from(photos.map((x) => x.toJson())),
            "Notes": List<dynamic>.from(notes.map((x) => x.toJson())),
        };
    }
    
    class Note {
        String note;
    
        Note({
            this.note,
        });
    
        factory Note.fromJson(Map<String, dynamic> json) => Note(
            note: json["Note"],
        );
    
        Map<String, dynamic> toJson() => {
            "Note": note,
        };
    }
    
    class Photo {
        String photoUrl;
    
        Photo({
            this.photoUrl,
        });
    
        factory Photo.fromJson(Map<String, dynamic> json) => Photo(
            photoUrl: json["PhotoUrl"],
        );
    
        Map<String, dynamic> toJson() => {
            "PhotoUrl": photoUrl,
        };
    }
    
    
    

    查看模型以进行解析。 并在文件中声明您的 json 以进行如上所述的解析。

    这是最终输出:

    I/flutter (23844): This is the employee name : EmployeeName
    I/flutter (23844): This is the employee id 1
    I/flutter (23844): This is the employee text Text
    I/flutter (23844): This are the notes : Note
    I/flutter (23844): This are the notes : Note
    

    现在看你如何在视图中使用它了

    【讨论】:

    • 查看我使用ui显示数据的编辑,你可以用你的方式编辑它
    【解决方案3】:

    您可以使用https://app.quicktype.io/ 轻松创建您的课程。 JSON to Dart > 只需将您的 JSON 粘贴到其中即可享受!

    【讨论】:

      【解决方案4】:

      ma​​in.dart

      import 'package:cached_network_image/cached_network_image.dart';
      import 'package:flutter/cupertino.dart';
      import 'package:flutter/material.dart';
      import 'package:flutter_demo/CategoryListModel.dart';
      import 'package:flutter_demo/GetCategoryListParser.dart';
      import 'package:fluttertoast/fluttertoast.dart';
      
      void main() {
        runApp(MyApp());
      }
      
      class MyApp extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
          return MaterialApp(
            title: 'Flutter Demo',
            theme: ThemeData(
              primarySwatch: Colors.blue,
            ),
            home: MyHomePage(title: 'Flutter Demo Home Page'),
          );
        }
      }
      
      class MyHomePage extends StatefulWidget {
        MyHomePage({Key? key, required this.title}) : super(key: key);
      
        final String title;
      
        @override
        _MyHomePageState createState() => _MyHomePageState();
      }
      
      class _MyHomePageState extends State<MyHomePage> {
        List<CategoryListModel> categoryList = <CategoryListModel>[];
      
        @override
        Widget build(BuildContext context) {
          return Scaffold(
            appBar: AppBar(
              title: Text("Flutter JSON"),
            ),
            body: FutureBuilder(
              future: getCategoryList(),
              builder: (context, snapshot) {
                return categories(categoryList);
              },
            ),
          );
        }
      
        Widget categories(List<CategoryListModel> list) {
          if (list != null && list.length > 0) {
            return GridView.count(
              crossAxisCount: 3,
              children: List.generate(list.length, (index) {
                return Container(
                  child: Column(
                    children: [
                      Container(
                        child: ClipRRect(
                          child: CachedNetworkImage(
                            fit: BoxFit.fill,
                            imageUrl: list[index].categoryImage,
                          ),
                        ),
                      ),
                      Text(
                        list[index].categoryName,
                      )
                    ],
                  ),
                );
              }),
            );
          } else {
            return Container();
          }
        }
      
        Future getCategoryList() async {
          Map result = await GetCategoryListParser.callApi(url);
          if (result["errorCode"] == 0) {
            categoryList = result["value"];
          } else {
            Fluttertoast.showToast(msg: result["value"]);
          }
        }
      }
      

      GetParser.dart

      import 'dart:async';
      import 'dart:convert';
      
      import 'package:flutter_demo/CategoryListModel.dart';
      import 'package:http/http.dart' as http;
      
      class GetCategoryListParser {
        static Future callApi(String url) async {
          final response = await http.get(Uri.parse(url)/*, headers: Config.httpGetHeader*/);
          final statusCode = response.statusCode;
          try {
            if (statusCode == 200) {
              Map body = json.decode(response.body);
              List categories = body["Categories"];
              List mainCategories = [];
              for (int i = 0; i < categories.length; i++) {
                Map<String, dynamic> map = categories[i];
                if (map['parent_category_id'] == 0) {
                  mainCategories.add(map);
                }
              }
              categories.clear();
              categories.addAll(mainCategories);
              List<CategoryListModel> categoryModelList =
              categories.map((c) => new CategoryListModel.parseForCategories(c)).toList();
              return {
                'errorCode': 0,
                'value': categoryModelList,
              };
            } else {
              return {'errorCode': "-1", 'msg': "Status Code Error"};
            }
          } catch (e) {
            print(e);
            return {'errorCode': "-1", 'msg': "$e"};
          }
        }
      }
      

      Model.dart

      class CategoryListModel {
        var categoryId, categoryName, categoryImage;
      
        CategoryListModel.parseForCategories(Map<String, dynamic> map) {
          if (map["id"] != null) {
            categoryId =map["id"];
          }
          if (map["name"] != null) {
            categoryName =map["name"];
          }
          if (map["image"] != null) {
            Map images =map["image"];
            if (images["src"] != null) {
              categoryImage = images["src"];
            }
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2020-09-12
        • 2020-05-19
        • 2020-04-04
        • 2020-12-25
        • 2019-10-21
        • 2021-03-06
        • 1970-01-01
        • 2019-07-27
        • 2019-06-26
        相关资源
        最近更新 更多