首页 > 解决方案 > 如何在没有特定结构的情况下提取特定的 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
    );
  }
}

编辑:如果字段不总是以相同的顺序返回怎么办?

标签: flutter

解决方案


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"


推荐阅读