解散Json扑腾

问题描述 投票:0回答:3

我正在学习扑动并试图解析一个像这样的数组或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函数,它从服务器获取这些数据。

 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,
    );
  }
}

我在上面的代码中做错了什么? Thanx提前!

dart flutter
3个回答
0
投票

尝试使用

pics = data.map((i)=>Photo.fromJson(i)).toList();

您正在从服务器接收json数组而不是json对象


0
投票

尝试这个,如果它没有工作,请确保打印响应正文

Iterable<dynamic> l = json.decode(uriResponse.body);
List<Post> posts = l.map((model) => Post.fromJson(model)).toList();

0
投票

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


0
投票

在我的项目中,我做了这样的工作

pics = (data as List).map((model) => Photo.fromJson(model)).toList();
© www.soinside.com 2019 - 2024. All rights reserved.