首页 > 解决方案 > 解析复杂的 JSON Flutter

问题描述

我正在尝试将这些复杂的 JSON 数据解析为 Flutter 应用程序。我能够成功获取 JSON 数据,但无法在应用程序中显示数据。请参阅下面的代码和 JSON 数据。我做错了什么?

JSON数据

{
"response": {
    "cars": [
        [
            {
                "id": 1,
                "name": "Ford Mustang GT",
                "class": "Muscle Car"
            },
            {
                "id": 2,
                "name": "Dodge Challenger",
                "class": "Muscle Car"
            },
            {
                "id": 3,
                "name": "Chevrolet Camaro",
                "class": "Muscle Car"
            },
            {
                "id": 4,
                "name": "Pontiac Firebird",
                "class": "Muscle Car"
            }
        ]
    ]
}

}

数据模型

class Cars {
  Cars({
    this.id,
    this.name,
    this.carClass,
  });

  int id;
  String name;
  String carClass;

  factory Cars.fromJson(Map<String, dynamic> json) => Cars(
        id: json["id"],
        name: json["name"],
        carClass: json["class"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "class": carClass,
      };
}

API 服务获取 JSON 数据

class ApiService {
  Future<List<Cars>> getCars() async {
    http.Response response = await http.get('http://localhost:3000/response');

    var body;

    if (response.statusCode == 200) {
      body = jsonDecode(response.body);
      List<dynamic> carList = body['response'];
      print(body);
      List<Cars> res =
          carList.map((dynamic item) => Cars.fromJson(item)).toList();

      return res;
    }
  }
}

显示数据

标签: arraysjsonflutterparsingdart

解决方案


您可以使用此应用程序帮助构建类。( https://app.quicktype.io/ )

这些是您必须为获得的对象使用的类。请务必更改您认为相关的类的名称。

class Response {
    Response({
        this.response,
    });

    final ResponseClass response;

    factory Response.fromJson(Map<String, dynamic> json) => Response(
        response: ResponseClass.fromJson(json["response"]),
    );

    Map<String, dynamic> toJson() => {
        "response": response.toJson(),
    };
}

class ResponseClass {
    ResponseClass({
        this.cars,
    });

    final List<List<Car>> cars;

    factory ResponseClass.fromJson(Map<String, dynamic> json) => ResponseClass(
        cars: List<List<Car>>.from(json["cars"].map((x) => List<Car>.from(x.map((x) => Car.fromJson(x))))),
    );

    Map<String, dynamic> toJson() => {
        "cars": List<dynamic>.from(cars.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))),
    };
}

class Car {
    Car({
        this.id,
        this.name,
        this.carClass,
    });

    final int id;
    final String name;
    final String carClass;

    factory Car.fromJson(Map<String, dynamic> json) => Car(
        id: json["id"],
        name: json["name"],
        carClass: json["class"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "class": carClass,
    };
}

最后,替换这一行:

body = jsonDecode(response.body);
List<dynamic> carList = body['response'];
print(body);
List<Cars> res =
          carList.map((dynamic item) => Cars.fromJson(item)).toList();

有了这个:

return Response.fromJson(response.body);

并替换函数返回给 Response 的数据类型。


推荐阅读