【问题标题】:Flutter get Data from complex jsonFlutter 从复杂的 json 中获取数据
【发布时间】:2019-12-03 13:11:00
【问题描述】:

我想要这个 json 的“标题”

我只想要项目中的标题。 我可以通过 kind 或 etag 等项目获取每个数据,但 items 为空。 怎么获得称号??

var data = await http.get("https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={id}&maxResults=5&order=date&type=video&key={key}");
var jsonData =  json.decode(data.body);
String title = jsonData["items"][0]["title"];
{
    "kind": "youtube#searchListResponse",
    "etag": "\"Bdx4f4ps3xCOOo1WZ91nTLkRZ_c/g32qWHUfh9ZGLFfaJ4eAIWqe5As\"",
    "nextPageToken": "CAUQAA",
    "regionCode": "DE",
    "pageInfo": {
        "totalResults": 207,
        "resultsPerPage": 5
    },
    "items": [
        {
            "kind": "youtube#searchResult",
            "etag": "\"Bdx4f4ps3xCOOo1WZ91nTLkRZ_c/IPag1MLLCZWNOan8xL200XduRjk\"",
            "id": {
                "kind": "youtube#video",
                "videoId": "iWkAYZyrrWc"
            },
            "snippet": {
                "publishedAt": "2019-07-24T15:59:15.000Z",
                "channelId": "UC7TZhmZOk5nxVjBozb2EW4w",
                "title": "Afterbuy Statistiken - Performance Analyse und Controlling für Onlinehändler!",
                "description": "Die Afterbuy Statistik ist ein Auswertungstool zur Analyse der Performance eines Onlinehändlers im E-Commerce Markt. Wenn du den Mehrwert dieser Afterbuy ...",
                "thumbnails": {
                    "default": {
                        "url": "https://i.ytimg.com/vi/iWkAYZyrrWc/default.jpg",
                        "width": 120,
                        "height": 90
                    },
                    "medium": {
                        "url": "https://i.ytimg.com/vi/iWkAYZyrrWc/mqdefault.jpg",
                        "width": 320,
                        "height": 180
                  }
              }
          }
        }
      ]
   };
}

【问题讨论】:

    标签: json flutter


    【解决方案1】:

    您可以使用this 网站为您的响应生成模型类。

    或者你也可以看看这个:JSON and serialization

    并像下面这样使用它:

    // If server returns an OK response, parse the JSON.
    return YourModel.fromJson(json.decode(data.body));
    

    【讨论】:

      【解决方案2】:

      你错过了sn-p

      var title = jsonData()["items"][0].snippet["title"];
      console.log(title);
      
      function jsonData() {
         return {
        "kind": "youtube#searchListResponse",
        "etag": "\"Bdx4f4ps3xCOOo1WZ91nTLkRZ_c/g32qWHUfh9ZGLFfaJ4eAIWqe5As\"",
        "nextPageToken": "CAUQAA",
        "regionCode": "DE",
        "pageInfo": {
            "totalResults": 207,
            "resultsPerPage": 5
        },
        "items": [
            {
                "kind": "youtube#searchResult",
                "etag": "\"Bdx4f4ps3xCOOo1WZ91nTLkRZ_c/IPag1MLLCZWNOan8xL200XduRjk\"",
                "id": {
                    "kind": "youtube#video",
                    "videoId": "iWkAYZyrrWc"
                },
                "snippet": {
                    "publishedAt": "2019-07-24T15:59:15.000Z",
                    "channelId": "UC7TZhmZOk5nxVjBozb2EW4w",
                    "title": "Afterbuy Statistiken - Performance Analyse und Controlling für Onlinehändler!",
                    "description": "Die Afterbuy Statistik ist ein Auswertungstool zur Analyse der Performance eines Onlinehändlers im E-Commerce Markt. Wenn du den Mehrwert dieser Afterbuy ...",
                    "thumbnails": {
                        "default": {
                            "url": "https://i.ytimg.com/vi/iWkAYZyrrWc/default.jpg",
                            "width": 120,
                            "height": 90
                        },
                        "medium": {
                            "url": "https://i.ytimg.com/vi/iWkAYZyrrWc/mqdefault.jpg",
                            "width": 320,
                            "height": 180
                        }
                    }
                }
              }
            ]
         };
      }

      【讨论】:

        【解决方案3】:

        如果你只想要标题而不想创建模型(你真的应该 IMO)

        伪代码

        List<String> titlesList=new List<String>();
        if(jsonData.length != 0){
           if(jsonData["items"]!=null ){
             List itemsList = jsonData["items"];
              for(var item in itemsList){
               String title = item["snippet"]["title"];
               //ideally here you create your snippet object using a model and add it to a list of models
               //titlesList.add(title)
              }
           }
        }
        

        【讨论】:

          【解决方案4】:

          你应该创建一个模型如下。

          // 要解析此 JSON 数据,请执行以下操作 // // 最终结果 = resultFromJson(jsonString);

          import 'dart:convert';
          
          class Result {
              String kind;
              String etag;
              String nextPageToken;
              String regionCode;
              PageInfo pageInfo;
              List<Item> items;
          
              Result({
                  this.kind,
                  this.etag,
                  this.nextPageToken,
                  this.regionCode,
                  this.pageInfo,
                  this.items,
              });
          
              factory Result.fromRawJson(String str) => Result.fromJson(json.decode(str));
          
              String toRawJson() => json.encode(toJson());
          
              factory Result.fromJson(Map<String, dynamic> json) => new Result(
                  kind: json["kind"] == null ? null : json["kind"],
                  etag: json["etag"] == null ? null : json["etag"],
                  nextPageToken: json["nextPageToken"] == null ? null : json["nextPageToken"],
                  regionCode: json["regionCode"] == null ? null : json["regionCode"],
                  pageInfo: json["pageInfo"] == null ? null : PageInfo.fromJson(json["pageInfo"]),
                  items: json["items"] == null ? null : new List<Item>.from(json["items"].map((x) => Item.fromJson(x))),
              );
          
              Map<String, dynamic> toJson() => {
                  "kind": kind == null ? null : kind,
                  "etag": etag == null ? null : etag,
                  "nextPageToken": nextPageToken == null ? null : nextPageToken,
                  "regionCode": regionCode == null ? null : regionCode,
                  "pageInfo": pageInfo == null ? null : pageInfo.toJson(),
                  "items": items == null ? null : new List<dynamic>.from(items.map((x) => x.toJson())),
              };
          }
          
          class Item {
              String kind;
              String etag;
              Id id;
              Snippet snippet;
          
              Item({
                  this.kind,
                  this.etag,
                  this.id,
                  this.snippet,
              });
          
              factory Item.fromRawJson(String str) => Item.fromJson(json.decode(str));
          
              String toRawJson() => json.encode(toJson());
          
              factory Item.fromJson(Map<String, dynamic> json) => new Item(
                  kind: json["kind"] == null ? null : json["kind"],
                  etag: json["etag"] == null ? null : json["etag"],
                  id: json["id"] == null ? null : Id.fromJson(json["id"]),
                  snippet: json["snippet"] == null ? null : Snippet.fromJson(json["snippet"]),
              );
          
              Map<String, dynamic> toJson() => {
                  "kind": kind == null ? null : kind,
                  "etag": etag == null ? null : etag,
                  "id": id == null ? null : id.toJson(),
                  "snippet": snippet == null ? null : snippet.toJson(),
              };
          }
          
          class Id {
              String kind;
              String videoId;
          
              Id({
                  this.kind,
                  this.videoId,
              });
          
              factory Id.fromRawJson(String str) => Id.fromJson(json.decode(str));
          
              String toRawJson() => json.encode(toJson());
          
              factory Id.fromJson(Map<String, dynamic> json) => new Id(
                  kind: json["kind"] == null ? null : json["kind"],
                  videoId: json["videoId"] == null ? null : json["videoId"],
              );
          
              Map<String, dynamic> toJson() => {
                  "kind": kind == null ? null : kind,
                  "videoId": videoId == null ? null : videoId,
              };
          }
          
          class Snippet {
              DateTime publishedAt;
              String channelId;
              String title;
              String description;
              Thumbnails thumbnails;
          
              Snippet({
                  this.publishedAt,
                  this.channelId,
                  this.title,
                  this.description,
                  this.thumbnails,
              });
          
              factory Snippet.fromRawJson(String str) => Snippet.fromJson(json.decode(str));
          
              String toRawJson() => json.encode(toJson());
          
              factory Snippet.fromJson(Map<String, dynamic> json) => new Snippet(
                  publishedAt: json["publishedAt"] == null ? null : DateTime.parse(json["publishedAt"]),
                  channelId: json["channelId"] == null ? null : json["channelId"],
                  title: json["title"] == null ? null : json["title"],
                  description: json["description"] == null ? null : json["description"],
                  thumbnails: json["thumbnails"] == null ? null : Thumbnails.fromJson(json["thumbnails"]),
              );
          
              Map<String, dynamic> toJson() => {
                  "publishedAt": publishedAt == null ? null : publishedAt.toIso8601String(),
                  "channelId": channelId == null ? null : channelId,
                  "title": title == null ? null : title,
                  "description": description == null ? null : description,
                  "thumbnails": thumbnails == null ? null : thumbnails.toJson(),
              };
          }
          
          class Thumbnails {
              Default thumbnailsDefault;
              Default medium;
          
              Thumbnails({
                  this.thumbnailsDefault,
                  this.medium,
              });
          
              factory Thumbnails.fromRawJson(String str) => Thumbnails.fromJson(json.decode(str));
          
              String toRawJson() => json.encode(toJson());
          
              factory Thumbnails.fromJson(Map<String, dynamic> json) => new Thumbnails(
                  thumbnailsDefault: json["default"] == null ? null : Default.fromJson(json["default"]),
                  medium: json["medium"] == null ? null : Default.fromJson(json["medium"]),
              );
          
              Map<String, dynamic> toJson() => {
                  "default": thumbnailsDefault == null ? null : thumbnailsDefault.toJson(),
                  "medium": medium == null ? null : medium.toJson(),
              };
          }
          
          class Default {
              String url;
              int width;
              int height;
          
              Default({
                  this.url,
                  this.width,
                  this.height,
              });
          
              factory Default.fromRawJson(String str) => Default.fromJson(json.decode(str));
          
              String toRawJson() => json.encode(toJson());
          
              factory Default.fromJson(Map<String, dynamic> json) => new Default(
                  url: json["url"] == null ? null : json["url"],
                  width: json["width"] == null ? null : json["width"],
                  height: json["height"] == null ? null : json["height"],
              );
          
              Map<String, dynamic> toJson() => {
                  "url": url == null ? null : url,
                  "width": width == null ? null : width,
                  "height": height == null ? null : height,
              };
          }
          
          class PageInfo {
              int totalResults;
              int resultsPerPage;
          
              PageInfo({
                  this.totalResults,
                  this.resultsPerPage,
              });
          
              factory PageInfo.fromRawJson(String str) => PageInfo.fromJson(json.decode(str));
          
              String toRawJson() => json.encode(toJson());
          
              factory PageInfo.fromJson(Map<String, dynamic> json) => new PageInfo(
                  totalResults: json["totalResults"] == null ? null : json["totalResults"],
                  resultsPerPage: json["resultsPerPage"] == null ? null : json["resultsPerPage"],
              );
          
              Map<String, dynamic> toJson() => {
                  "totalResults": totalResults == null ? null : totalResults,
                  "resultsPerPage": resultsPerPage == null ? null : resultsPerPage,
              };
          }
          

          接下来做,

          var data = await http.get("https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={id}&maxResults=5&order=date&type=video&key={key}");
          var jsonData =  json.decode(data.body);
          return Result.fromJson(jsonData);
          

          此时它应该可以工作

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-10-21
            • 2017-09-15
            • 1970-01-01
            • 1970-01-01
            • 2018-11-29
            • 1970-01-01
            相关资源
            最近更新 更多