Flutter 中如何从这个 Json 中获取数据?
Posted
技术标签:
【中文标题】Flutter 中如何从这个 Json 中获取数据?【英文标题】:How Get Data from this Json in Flutter? 【发布时间】:2021-04-23 07:44:54 【问题描述】:
"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",
,
......
]
我不知道正确的方法应该是什么
如何从具有相同名称“数据”的对象的对象数组中获取数据
【问题讨论】:
这能回答你的问题吗? How to decode JSON in Flutter? 【参考方案1】:您必须像这样声明模型:
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'],
);
然后,您必须使用如下代码对其进行反序列化:
var results = jsonDecode(yourJsonString)["features"];
return (results as List)
.map((e) => DataModel(e))
.toList();
【讨论】:
【参考方案2】:从 JSON 获取数据时,您应该创建一个模型来描述您要解析的对象(在本例中为 Data
对象)。然后,您可以创建一个方法来从 JSON 字符串中解析该对象(或对象列表):
对象将如下所示:
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,
;
然后您可以像这样解析对象:
// 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"])));
对于模型创建,为了节省时间,您还可以查看this tool。它支持从您的 JSON 字符串创建模型。
【讨论】:
以上是关于Flutter 中如何从这个 Json 中获取数据?的主要内容,如果未能解决你的问题,请参考以下文章