json 将Map转换为对象给予空属性对象

xmjla07d  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(87)

这是Retrofit为我构建的代码,我对它做了一些修改。
_result是一个Response<Map<String,dynamic>>,它是通过dio.fetch()获取的。

List<ArticleModel> value = _result.data!['articles']
        .map<ArticleModel>(
            (dynamic i) => ArticleModel.fromJson(i as Map<String, dynamic>))
        .toList();

字符串
下面是fromJson ArticleModel构造函数

class ArticleModel extends ArticleEntity {
  const ArticleModel({
    int? id,
    String? author,
    String? title,
    String? description,
    String? url,
    String? urlToImage,
    String? publishedAt,
    String? content,
  });

  factory ArticleModel.fromJson(Map<String, dynamic> map) {
    return ArticleModel(
      author: map['author'] ?? '',
      title: map['title'] ?? '',
      description: map['description'] ?? '',
      url: map['url'] ?? '',
      urlToImage: map['urlToImage'] ?? '',
      publishedAt: map['publishedAt'] ?? '',
      content: map['content'] ?? '',
    );
  }
}


我添加了一些日志,但第二个日志给了我一个空属性的对象

log(_result.data!['articles'][0]['title'], name: 'title'); -> gives me correct title string

    List<ArticleModel> value = _result.data!['articles']
        .map<ArticleModel>(
            (dynamic i) => ArticleModel.fromJson(i as Map<String, dynamic>))
        .toList();

    log(value[0].toString(), name: 'articleModel'); -> gives me ArticleModel(null, null, ...)

mbzjlibv

mbzjlibv1#

我不得不这么做

class ArticleModel extends ArticleEntity {
  const ArticleModel({
    id,
    author,
    title,
    description,
    url,
    urlToImage,
    publishedAt,
    content,
  }) : super(
          id: id,
          author: author,
          title: title,
          description: description,
          url: url,
          urlToImage: urlToImage,
          publishedAt: publishedAt,
          content: content,
        );

字符串
感谢dragonfly02

相关问题