简体   繁体   English

无法使用Flutter项目将DSON映射到Dart中的List

[英]Cannot map JSON to List in Dart using a Flutter project

I was running Flutter 1.0.0 (first release) and recently upgraded to 1.2.1 and there were a lot of errors and warnings that I had to correct. 我正在运行Flutter 1.0.0(第一版)并且最近升级到1.2.1并且有很多错误和警告我必须纠正。 Mostly specifying annotation types. 主要指定注释类型。 After correcting all of these I ran my Android app and now the code that maps JSON to a List is not working. 在纠正了所有这些后,我运行了我的Android应用程序,现在将JSON映射到List的代码无效。 First I'll post my original code that worked. 首先,我将发布有效的原始代码。 The JSON data is from an HTTP request. JSON数据来自HTTP请求。

api.dart api.dart

Future<List<Device>> getDevices() async {
  var response = await _httpNetwork.get(_devicesUrl, headers: {"Cookie": _sessionId});

  if (response.statusCode < 200 || response.statusCode > 400) {
    throw Exception("Error while fetching data");
  }

  final body = json.decode(response.body);

  return body.map<Device>((device) => Device.fromJson(device)).toList();
}

device.dart device.dart

class Device {
  Device({
    this.id,
    this.name,
    this.uniqueId,
    this.status,
    this.phone,
    this.model,
    this.disabled,
  });

  factory Device.fromJson(Map<String, dynamic> json) => Device(
        id: json['id'],
        name: json['name'],
        uniqueId: json['uniqueId'],
        status: json['status'] == 'online' ? true : false,
        phone: json['phone'],
        model: json['model'],
        disabled: json['disabled'],
      );

  // API data
  int id;
  String name;
  String uniqueId;
  bool status;
  String phone;
  String model;
  bool disabled;

  Map<String, dynamic> toJson() => <String, dynamic>{
        'id': id,
        'name': name,
        'uniqueId': uniqueId,
        'status': status == true ? 'online' : 'offline',
        'phone': phone,
        'model': model,
        'disabled': disabled,
      };
}

Now here is where the issues arises with the following change in api.dart . 现在这里是api.dart发生以下变化时出现问题的api.dart

return json.decode(response.body).map<Device>((Map<String, dynamic> device) => Device.fromJson(device)).toList();

While this syntax is correct according to Android Studio/Flutter/Dart it doesn't seem to work. 根据Android Studio / Flutter / Dart,这种语法是正确的,但它似乎不起作用。 The app doesn't crash nor do I get errors in the run console, it just hits my onError code in my Observable<bool>.fromFuture() call. 应用程序不会崩溃,也不会在运行控制台中出现错误,它只是在我的Observable<bool>.fromFuture()调用中遇到我的onError代码。

I put print calls in my code to determine the return statement in api.dart was the culprit. 我在我的代码中放置了print调用来确定api.dart中的return语句是罪魁祸首。 Anyone have any insight into this issue? 任何人都对此问题有任何见解?

I think instead of this 我想而不是这个

final body = json.decode(response.body);
  return body.map<Device>((device) => Device.fromJson(device)).toList();

you should do this 你应该做这个

  final body = json.decode(response.body).cast<Map<String, dynamic>>();
 return body.map<Device>((json) => Device.fromJson(json)).toList();

Try this way make pojo class for response data.. 试试这种方式为响应数据制作pojo类。

class UserData {
final int albumId;
final int id;
final String title;
final String url;
final String thumbnailUrl;

UserData({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});

factory UserData.fromJson(Map<String, dynamic> json) {
return new UserData(
    albumId: json['albumId'],
    id: json['id'],
    title: json['title'],
    url: json['url'],
    thumbnailUrl: json['thumbnailUrl']);
}
}

make method for fetch data.. make方法获取数据..

Future<UserData> fetchData() async {
var result = await get('https://jsonplaceholder.typicode.com/photos');

if (result.statusCode == 200) {
 return UserData.fromJson(json.decode(result.body));
} else {
 // If that response was not OK, throw an error.
 throw Exception('Failed to load post');
}
}

now make list object like this way.. 现在以这种方式制作列表对象..

 Future<UserData> userDataList;

click on button.. 点击按钮..

            userDataList = fetchData();

you can also used this below code for list of data.. 您也可以使用以下代码获取数据列表..

List<UserData> list = List();
 var isLoading = false;

void fetchData() async {
setState(() {
  isLoading = true;
});
final response = await get("https://jsonplaceholder.typicode.com/photos");
if (response.statusCode == 200) {
  list = (json.decode(response.body) as List)
      .map((data) => UserData.fromJson(data))
      .toList();
  setState(() {
    isLoading = false;
  });
} else {
  throw Exception('Failed to load photos');
}
}

I tried this code and it is working, one side note, your status is of type bool but you are giving it a string variable, be aware about that. 我尝试了这个代码并且它正在工作,一方面注意,你的statusbool类型,但你给它一个字符串变量,请注意这一点。 and also the json.decode(response.body) will return to you the sample response i added in the code, so you don't need to change it. 并且json.decode(response.body)将返回我在代码中添加的示例响应,因此您无需更改它。 Hope it helps! 希望能帮助到你!

class Device {
  Device({
    this.id,
    this.name,
    this.uniqueId,
    this.status,
    this.phone,
    this.model,
    this.disabled,
  });

  factory Device.fromJson(Map<String, dynamic> json) => Device(
        id: json['id'],
        name: json['name'],
        uniqueId: json['uniqueId'],
        status: json['status'] == 'online' ? true : false,
        phone: json['phone'],
        model: json['model'],
        disabled: json['disabled'],
      );

  // API data
  int id;
  String name;
  String uniqueId;
  bool status;
  String phone;
  String model;
  bool disabled;

  Map<String, dynamic> toJson() => <String, dynamic>{
        'id': id,
        'name': name,
        'uniqueId': uniqueId,
        'status': status == true ? 'online' : 'offline',
        'phone': phone,
        'model': model,
        'disabled': disabled,
      };
}




void main() {
  var resp = [{"id": 1, "name": "Pixel", "uniqueId": "439610961385665", 
               "status": "online", "phone": "3215551234", "model": "XL", "disabled": false}];

  List json = resp;
  for(var item in json){
    Device device  = Device.fromJson(item);
    print("nameDevice: ${device.status}");
  }

}

这是修复此问题的更改。

return json.decode(response.body).map<Device>((dynamic device) => Device.fromJson(device)).toList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM