如何在颤振中解析 JSON 文件

时间:2021-06-11 10:19:37

标签: json flutter parsing dart

我在调用 API 时遇到错误,我无法解析 bean 类中的数据。

我的 API 服务代码是:

  // Get all Hotels list from the API url
  Future<List<Hotel>> getHotels() async {
    final response = await http.get(Uri.parse(apiUrl));

    ///// checking the status code is successful
    if (response.statusCode == 200) {
      // print(response.body);
      return getHotelList(response.body);
    } else {
      throw Exception('Unable to fetch data from API');
    }
  }


  ////// Convert response to Hotel object List
  List<Hotel> getHotelList(String responseBody) {
 //  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
    final parsed = json.decode(responseBody).cast<String,dynamic>();
    return parsed.map<Hotel>((json) => Hotel.fromJson(json)).toList();
  }

我的 Beans 类是

class Hotel {
  int status;
  List<Data> data;

  Hotel({this.status, this.data});

  Hotel.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    if (json['data'] != null) {
      data = new List<Data>();
      json['data'].forEach((v) {
        data.add(new Data.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['status'] = this.status;
    if (this.data != null) {
      data['data'] = this.data.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Data {
  int id;
  String title;
  String description;
  String address;
  String postcode;
  String phoneNumber;
  String latitude;
  String longitude;
  Image image;

  Data(
      {this.id,
        this.title,
        this.description,
        this.address,
        this.postcode,
        this.phoneNumber,
        this.latitude,
        this.longitude,
        this.image});

  Data.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    title = json['title'];
    description = json['description'];
    address = json['address'];
    postcode = json['postcode'];
    phoneNumber = json['phoneNumber'];
    latitude = json['latitude'];
    longitude = json['longitude'];
    image = json['image'] != null ? new Image.fromJson(json['image']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['title'] = this.title;
    data['description'] = this.description;
    data['address'] = this.address;
    data['postcode'] = this.postcode;
    data['phoneNumber'] = this.phoneNumber;
    data['latitude'] = this.latitude;
    data['longitude'] = this.longitude;
    if (this.image != null) {
      data['image'] = this.image.toJson();
    }
    return data;
  }
}

class Image {
  String small;
  String medium;
  String large;

  Image({this.small, this.medium, this.large});

  Image.fromJson(Map<String, dynamic> json) {
    small = json['small'];
    medium = json['medium'];
    large = json['large'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['small'] = this.small;
    data['medium'] = this.medium;
    data['large'] = this.large;
    return data;
  }
}

我得到的错误是

E/flutter (30141): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: Class 'CastMap<String, dynamic, String, dynamic>' has no instance method 'map' with matching arguments.
E/flutter (30141): Receiver: Instance of 'CastMap<String, dynamic, String, dynamic>'
E/flutter (30141): Tried calling: map<Hotel>(Closure: (dynamic) => Hotel)
E/flutter (30141): Found: map<K2, V2>((K, V) => MapEntry<K2, V2>) => Map<K2, V2>
E/flutter (30141): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)

通过 API 服务文件中的以下代码将数据解析为列表时,似乎会产生错误。

  List<Hotel> getHotelList(String responseBody) {
 //  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
    final parsed = json.decode(responseBody).cast<String,dynamic>();
    return parsed.map<Hotel>((json) => Hotel.fromJson(json)).toList();
  }

能否请您检查并指导我如何解决此问题?对此的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

List<Hotel> getHotelList(String responseBody) {
    final parsed = json.decode(responseBody);
    final List<dynamic> hotels = parsed["data"];
    return hotels.map((json) => Hotel.fromJson(json)).toList();
  }