dart - flutter中解析Json

标签 dart flutter

我正在学习 flutter 并尝试解析 json,它是数组或像这样的 json 对象。

[
  {
    "albumId": 1,
    "id": 1,
    "title": "accusamus beatae ad facilis cum similique qui sunt",
    "url": "https://via.placeholder.com/600/92c952",
    "thumbnailUrl": "https://via.placeholder.com/150/92c952"
  },
  {
    "albumId": 1,
    "id": 2,
    "title": "reprehenderit est deserunt velit ipsam",
    "url": "https://via.placeholder.com/600/771796",
    "thumbnailUrl": "https://via.placeholder.com/150/771796"
  },]

这是我的获取函数,它从服务器获取此数据。

 fetch() async{

   var client = new http.Client();
  try {
  var uriResponse = await 
  client.get('https://jsonplaceholder.typicode.com/photos');
  if(uriResponse.statusCode == 200){

  var data = json.decode(uriResponse.body);//data is array of objects
  List<Photo> pics= data.map((Map<String,dynamic> model)=> Photo.fromJson(model)).toList();
  setState(() {
    photos = data;
    _isLoading = false;
  });
}
  } finally {
client.close();
  }
}

但是这条线;

List<Photo> pics= data.map((Map<String,dynamic> model)=> Photo.fromJson(model)).toList();

给我错误:

ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type '(Map<String, dynamic>, dynamic) => Photo' is not a subtype of type '(dynamic) => dynamic' of 'f'

这是我的 Photo PODO 类。

  class Photo {
  final int id;
  final String title;
  final String url;
  final String thumbnailUrl;

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

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

上面的代码我做错了什么?提前致谢!

最佳答案

您可以使用quicktype它允许您复制 JSON 字符串并生成 Dart 对象

关于dart - flutter中解析Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55606123/

相关文章:

flutter - 为什么列表是绑定(bind)的?

flutter - 为什么这个 Flutter Cubit 在省略关键字 'required' 时会抛出错误?

android - Flutter WebView window.close()不起作用(Android)

flutter test enterText on widget 扩展 EditableText "Bad state: No element": building editable text for mention

json - 在 Flutter/Dart 中解析列表

json - 如何在 dart 中映射动态 json api 响应

dart - 如何在 Flutter 上持续检查互联网连接与否?

github - 如何在 Flutter 中添加来自 GitHub 的包?

Flutter 圆形波纹效果 : How to build beautiful material BottomNavigationBar

dart - Flutter NotificationListener with ScrollNotification vs ScrollController