简体   繁体   中英

How Get Data from this Json in Flutter?

 { "features": [ { "Data": { "First Name": "AA1", "Last Name": "AA2", "Address": "AA3", "Company": "AA4", } }, "Data": { "First Name": "BB1", "Last Name": "BB2", "Address": "BB3", "Company": "BB4", } }, { "Data": { "First Name": "CC1", "Last Name": "CC2", "Address": "CC3", "Company": "CC4", } }, ...... ] }

I have no idea what the right way to do this should be

How can i get Data from array of object of object with same name "Data"

When getting data from JSON, you should create a Model to describe the object you want to parse (in this case Data object). You can then create a method to parse that object (or a list of objects) from the JSON string:

The object will look like:

class Data {
    Data({
        this.firstName,
        this.lastName,
        this.address,
        this.company,
    });

    String firstName;
    String lastName;
    String address;
    String company;

    factory Data.fromJson(Map<String, dynamic> json) => Data(
        firstName: json["First Name"],
        lastName: json["Last Name"],
        address: json["Address"],
        company: json["Company"],
    );

    Map<String, dynamic> toJson() => {
        "First Name": firstName,
        "Last Name": lastName,
        "Address": address,
        "Company": company,
    };
}

You can then parse the object like this:

// features will be the list of your JSON objects
var features = jsonData["features"]; 

// Here you parse it to the list of Data object
var datas = List<Data>.from(features.map((item) => Data.fromJson(item["Data"])));

For the Model creating, to save time you can also check out this tool . It supports creating the Model from your JSON string.

You must to declare a model like these:

class Feature {
    Feature(DataModel dataModel);
}

class DataModel {
  DataModel(
      {firstName: firstName, lastName: lastName, address: address, company: company});

  factory DataModel.fromJson(Map<String, dynamic> json) {
    return DataModel(
      firstName: json['firstName'],
      lastName: json['lastName'],
      address: json['address'],
      company: json['company'],
    );
  }
}

And after that, you must to deserialize it using a code like this:

var results = jsonDecode(yourJsonString)["features"];

return (results as List)
    .map((e) => DataModel(e))
    .toList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM