flutter - 如何在没有特定结构的情况下提取特定的 json 字段
问题描述
我正在开发一个从无头站点运行的颤振应用程序。我正在研究为字段和值解析 JSON 对象。像这样的东西:
{
"content": {
"fields": [{
"label": "Vehicle Type",
"fieldFormattedVal": "Cars and Trucks"
}, {
"label": "Brand",
"fieldFormattedVal": "JLB Racing"
}, {
"label": "Model",
"fieldFormattedVal": "Cheetah"
}, {
"label": "Scale",
"fieldFormattedVal": "1\/10"
}, {
"label": "Completion Level",
"fieldFormattedVal": "Ready-to-Run"
}, {
"label": "Body Type",
"fieldFormattedVal": "Basher"
}, {
"label": "Ground Clearance",
"fieldFormattedVal": false
}, {
"label": "Tire Diameter",
"fieldFormattedVal": false
}, {
"label": "Motor Type",
"fieldFormattedVal": "Brushless"
}]
}
}
目前我能够获得具有特定结构的字段,如 json['content']['id'],但我不知道如何获得像 Vehicle Type 这样的单个字段。
我如何调整此功能以处理各个字段?
class Vehicle {
final String id;
final String title;
final String url;
final String defImage;
final String vehicleType;
final String brand;
Vehicle({this.id, this.title, this.url, this.defImage, this.vehicleType, this.brand});
factory Vehicle.fromJson(Map<String, dynamic> json) {
return Vehicle(
id: json['id'] ?? '',
title: json['title'] ?? '',
url: json['[url]'] ?? '',
defImage: json['[fileName]'] ?? '',
//vehicleType
//brand
);
}
}
编辑:如果字段不总是以相同的顺序返回怎么办?
解决方案
var response = await http.get(url);
var data = json.decode(response.body);
var vehicalType = data['content']['fields'][0]['label'];//will get you "Vehicle Type"
var brand = data['content']['fields'][1]['label'];//will get you "Brand"
推荐阅读
- python - 随机 pycache 文件夹生成 - 编码新手
- google-sheets-formula - 使用 Google 表格查询公式使某些列不重复值
- html - 增长元素以适应内容,但不要超过父元素
- python - AttributeError:模块“scapy.all”没有属性“RAW”
- python - 在 pandas 中在哪里添加多索引级别?
- python - Python:反转列表中的每 2 个项目
- javascript - (plugin babel) Error: Plugin/Preset files are not allowed to export objects, only functions
- ruby-on-rails - 我可以忽略 `node_modules`、`tmp` 和 `storage` 文件夹吗?
- python - 是否可以通过循环将这些有问题的元素更改为零以保持可持续性?
- python - 使用 Python OpenCV 检测图像中的所有圆圈(光学标记识别)