如何在flutter中处理json API数组

xmq68pz9  于 2023-02-09  发布在  Flutter
关注(0)|答案(1)|浏览(123)

我正在为我的flutter应用程序从newsapi获取数据。如何在这个json数据中获取源代码的id?

{
"status": "ok",
"totalResults": 38,


"articles": [

{  

"source": {
"id": "independent",
"name": "Independent"
},
"author": "Rachel Sharp",
"title": "Idaho murders - updates: Moscow police spark confusion over ‘targeted’ attack as crime scene results come back - The Independent",
"description": "Update on Idaho student murders",
"url": example.com,
"urlToImage": example.com,
"publishedAt": "2022-12-01T09:53:10Z",
"content": "ICYMI: Neighbour of victims hits out at Reddit sleuths\r\nA neighbour of the four University of Idaho students who were murdered on 13 November has hit out at Reddit sleuths who claimed that his media"
},
}

ArticleModel.dart

class ArticleModel {
  String? author;
  String? title;
  String? description;
  String? url;
  String? urlToImage;
  String? content;
  String? publishedAt;

  ArticleModel({required this.author, required this.title, required this.description, required this.url, required this.urlToImage, required this.content, required this.publishedAt});
}

SourceModel.dart

class SourceModel {
  String id;
  String name;
  String description;
  String url;
  String category;
  String country;
  String language;

  SourceModel({required this.id, required this.name, required this.description, required this.url, required this.category,
      required this.country, required this.language});
}

此方法返回可用源的列表

class SourceListClass {
  List<SourceModel> source = [];

  Future<void> getSourceList() async {
    String url = "https://newsapi.org/v2/top-headlines/sources?country=us&apiKey=45dd80f272ae40d5af76a796acee8529";

    var response = await http.get(Uri.parse(url));

    var jsonData = jsonDecode(response.body);

    if (jsonData['status'] == 'ok') {
      jsonData['sources'].forEach((element) {

        if (element['name'] != null) {

          SourceModel sourceModel = SourceModel(
            id: element['id'],
            name: element['name'],
            description: element['description'],
            url: element['url'],
            category: element['category'],
            country: element['country'],
            language: element['language'],
          );

          source.add(sourceModel);
        }
      });
    }
    print("");
  }
}

使用这种方法,我得到了其他数据,除了源没有问题。
Articles.dart

class News {
  List<ArticleModel> news = [];

  Future<void> getNews() async {
    String url = "https://newsapi.org/v2/top-headlines?country=us&apiKey=45dd80f272ae40d5af76a796acee8529";

    var response = await http.get(Uri.parse(url));

    var jsonData = jsonDecode(response.body);

    if (jsonData['status'] == 'ok') {
      jsonData['articles'].forEach((element) {

        if (element['urlToImage'] != null && element['description'] != null) {

          ArticleModel articleModel = ArticleModel(
            title: element['title'],
            author: element['author'],
            description: element['description'],
            url: element['url'],
            urlToImage: element['urlToImage'],
            content: element['context'],
            publishedAt: element['publishedAt'],
          );
          news.add(articleModel);
        }
      });
    }
  }
}

我想把源代码的id加到这个方法中

lnvxswe2

lnvxswe21#

您可以使用以下命令访问源的ID:

var id = element['source']['id'];

完整示例:

class News {
  List<ArticleModel> news = [];

  Future<void> getNews() async {
    String url = "https://newsapi.org/v2/top-headlines?country=us&apiKey=45dd80f272ae40d5af76a796acee8529";

    var response = await http.get(Uri.parse(url));

    var jsonData = jsonDecode(response.body);

    if (jsonData['status'] == 'ok') {
      jsonData['articles'].forEach((element) {

        if (element['urlToImage'] != null && element['description'] != null) {
          
          // get id of source
          var id = element['source']['id'];

          ArticleModel articleModel = ArticleModel(
            title: element['title'],
            author: element['author'],
            description: element['description'],
            url: element['url'],
            urlToImage: element['urlToImage'],
            content: element['context'],
            publishedAt: element['publishedAt'],
          );
          news.add(articleModel);
        }
      });
    }
  }
}

希望有帮助!:)

相关问题