代码之家  ›  专栏  ›  技术社区  ›  Adithya Shetty

如何从dart的Json文件中读取对象并映射到变量?

  •  0
  • Adithya Shetty  · 技术社区  · 6 年前

    JSON文件如下:

    [
        {
            "employee1": {
                "firstName": "Lokesh",
                "lastName": "Gupta",
                "website": "howtodoinjava.com"
            }
        },
        {
            "employee2": {
                "firstName": "Brian",
                "lastName": "Schultz",
                "website": "example.com"
            }
        }
    ]
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   Yadu    6 年前

    将上面的json列表提供给 json.decode()

    var dJson = json.decode(list);
    //which results in dJson being a List<dynamic>
    //access the first result
    var first = dJson[0];
    //which gives you a Map because the json.decode maintains the structure of the json given
    var employee1 = first["employee1"];
    //will give you another Map
    var firstName = employee1["firstName"];
    //will give you the firstName
    print(firstName);//Lokesh
    
        2
  •  0
  •   Darsh Shah    6 年前

    首先,尝试用您得到的JSON创建一个模型。为样本提供模型,如下所示。

    class EmployeeModel {
      Employee1 employee1;
    
      EmployeeModel({this.employee1});
    
      EmployeeModel.fromJson(Map<String, dynamic> json) {
        employee1 = json['employee1'] != null
            ? new Employee1.fromJson(json['employee1'])
            : null;
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        if (this.employee1 != null) {
          data['employee1'] = this.employee1.toJson();
        }
        return data;
      }
    }
    
    class Employee1 {
      String firstName;
      String lastName;
      String website;
    
      Employee1({this.firstName, this.lastName, this.website});
    
      Employee1.fromJson(Map<String, dynamic> json) {
        firstName = json['firstName'];
        lastName = json['lastName'];
        website = json['website'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['firstName'] = this.firstName;
        data['lastName'] = this.lastName;
        data['website'] = this.website;
        return data;
      }
    }
    

    然后使用

    EmployeeModel employee = EmployeeModel.fromJson(responseJSON);
    

        3
  •  0
  •   Sagar Acharya    6 年前

    看看我创建的这个例子: 下面是您提供的json。

    [
        {
            "employee1": {
                "firstName": "Lokesh",
                "lastName": "Gupta",
                "website": "howtodoinjava.com"
            }
        },
        {
            "employee2": {
                "firstName": "Brian",
                "lastName": "Schultz",
                "website": "example.com"
            }
        }
    ]
    
    

    解决方法如下:

    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(home: HomePage());
      }
    }
    
    class Employee {
      String firstName;
      String lastName;
      String website;
    
      Employee({this.firstName, this.lastName, this.website});
    }
    
    class HomePage extends StatefulWidget {
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      bool _isLoading = false;
    
      List<Employee> employeeList = List();
    
      @override
      void initState() {
        super.initState();
        getData();
      }
    
      getData() async {
        String data =
            await DefaultAssetBundle.of(context).loadString("json/parse.json");
    
        var jsonData = json.decode(data);
    
        jsonData.forEach((item) {
          item.forEach((key, value) {
            employeeList.add(Employee(
                firstName: value['firstName'],
                lastName: value['lastName'],
                website: value['website']));
          });
        });
    
        print(employeeList.length);
    
        employeeList.forEach((item) {
          print(item.firstName);
          print(item.lastName);
          print(item.website);
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(body: Text(''));
      }
    }