Flutter中的复杂JSON解析

时间:2019-12-21 11:35:56

标签: json flutter dart

我需要在我的应用程序中创建一张卡,但是我的应用程序是新闻应用程序,并使用JSON API从网站上调用我的数据,我试图在该应用程序中检索崩溃时的新闻图像并给出一条消息:

  

图像资源服务捕获的异常解析图像编码解码器时引发了以下ArgumentError:无效的参数:URI文件:/// medium_large中未指定主机。图片提供者:NetworkImage(“ medium_large”,比例尺:1.0)   图片键:NetworkImage(“ medium_large”,scale:1.0)

代码有什么问题?我可以更好地简化代码吗?

JSON:

{
    "status": "ok",
    "posts": [
        {
            "title": "Barcelona 0-0 Real Madrid: Bale goal disallowed in tense Clasico",
            "content": "Gareth Bale saw a goal disallowed as Barcelona and Real Madrid played out a 0-0 draw at Camp Nou on Wednesday. LaLiga's top two went into the contest level on points this season and with 72 wins each from previous league meetings, and there was nothing to separate them in a tense clash in Catalonia. The match was rearranged from October after the initial date became a security risk due to the prospect of Catalan independence protests, and there were fans inside and outside the stadium making their voices heard over one of Spain's most divisive issues.",
            "date": "2019-12-21 11:27:25",
            "thumbnail_image": {
                "medium_large": {
                    "url": "https://www.livescore.com/newsapi/04/soccer/imageret/barcelona-real-madrid-gareth-bale-goal-disallowed-tense-clasico-7-1cgsl7i8ipuf61gmt7m8ttd60w.jpg"
                }
            }
        }
    ]
}

新闻类:

class News {
  String status;
  List<Posts> posts;

  News({
    this.status,
    this.posts,
  });

  factory News.fromJson(Map<String, dynamic> json) => new News(
        status: json["status"],
        posts:
            new List<Posts>.from(json["posts"].map((x) => Posts.fromJson(x))),
      );

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

class Posts {
  String title;
  String content;
  DateTime date;
  PostImage thumbnailImages;

  Posts({this.title, this.content, this.date, this.thumbnailImages});

  factory Posts.fromJson(Map<String, dynamic> postsJson) => new Posts(
        title: postsJson["title"],
        content: postsJson["content"] == null ? null : postsJson["content"],
        date: DateTime.parse(postsJson["date"]),
        thumbnailImages: PostImage.fromJson(postsJson["thumbnail_images"]),
      );

  Map<String, dynamic> toJson() => {
        "title": title,
        "content": content == null ? null : content,
        "date": date.toIso8601String(),
        "thumbnail_images": thumbnailImages.toJson(),
      };
}

class PostImage {
  String mediumImage;
  String url;

  PostImage({ this.mediumImage, this.url });

  factory PostImage.fromJson(Map<String, dynamic> imgJson) => new PostImage(
      mediumImage: "medium_large",
  );

  Map<String, dynamic> toJson() => {
    "medium_large": mediumImage,
  };
}

列表新闻:

class ListItem extends StatelessWidget {
  final Posts posts;

  ListItem(this.posts);

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Row(
          textDirection: TextDirection.rtl,
      children: <Widget>[
        Container(
          height: 400,
          width: 220,
          child: Image.network(posts.thumbnailImages.mediumImage),
        ),
        Expanded(
          child: Padding(
            padding: EdgeInsets.all(8),
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    posts.title,
                    overflow: TextOverflow.ellipsis,
                    textAlign: TextAlign.right,
                    maxLines: 2,
                    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                  ),
                ]),
          ),
        )
      ],
    ));
  }
}

2 个答案:

答案 0 :(得分:1)

尝试添加.url

child: Image.network(posts.thumbnailImages.mediumImage.url),

工作代码: Gist

答案 1 :(得分:0)

您必须更改您的PostImage类。并添加另一个类MediumLarge

class PostImage {
  MediumLarge mediumLarge;

  PostImage({
    this.mediumLarge,
  });

  factory PostImage.fromJson(Map<String, dynamic> json) => PostImage(
        mediumLarge: MediumLarge.fromJson(json["medium_large"]),
      );

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

class MediumLarge {
  String url;

  MediumLarge({
    this.url,
  });

  factory MediumLarge.fromJson(Map<String, dynamic> json) => MediumLarge(
        url: json["url"],
      );

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

然后使用

Container(
  height: 400,
  width: 220,
  child: Image.network(posts.thumbnailImages.mediumImage.url),
)

有一个网站会为json生成飞镖类。 QuickType