Decode Json from Youtube api on Flutter












0














I make a call to Youtube API and get this Json:



     "kind": "youtube#videoListResponse",
"etag": ""XI7nbFXulYBIpL0ayR_gDh3eu1k/s7-xmHXpuqQxYzDp_wxhm59K4LE"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": ""XI7nbFXulYBIpL0ayR_gDh3eu1k/pajQ7iBy-7A0V_owifxkw-Kbw-Y"",
"id": "7lCDEYXw3mM",
"snippet": {
"publishedAt": "2012-06-20T23:12:38.000Z",
"channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
"title": "Google I/O 101: Q&A On Using Google APIs",
"description": "Antonio Fuentes speaks to us and takes questions on working with Google APIs and OAuth 2.0.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/7lCDEYXw3mM/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/7lCDEYXw3mM/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/7lCDEYXw3mM/hqdefault.jpg",
"width": 480,
"height": 360
}


But now I want to parse it and get just 3 nodes:




  1. Title

  2. Description

  3. The url for the default thumbnail


Indeed I get the Json response and can see it on the logs, but when try to parse it every time it fails.



This is my code:



final response = await http.get(
'https://www.googleapis.com/youtube/v3/videos?id=HEREGOESMYAPIKEY&part=snippet&id=T0Jqdjbed40');

final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
String title = parsed['items']['snippet']['title'];
print(title);
String description = parsed['items']['snippet']['description'];
print(description);
String thumbnail = parsed['items']['snippet']['thumbnails']['default']['url'];
print(thumbnail);









share|improve this question





























    0














    I make a call to Youtube API and get this Json:



         "kind": "youtube#videoListResponse",
    "etag": ""XI7nbFXulYBIpL0ayR_gDh3eu1k/s7-xmHXpuqQxYzDp_wxhm59K4LE"",
    "pageInfo": {
    "totalResults": 1,
    "resultsPerPage": 1
    },
    "items": [
    {
    "kind": "youtube#video",
    "etag": ""XI7nbFXulYBIpL0ayR_gDh3eu1k/pajQ7iBy-7A0V_owifxkw-Kbw-Y"",
    "id": "7lCDEYXw3mM",
    "snippet": {
    "publishedAt": "2012-06-20T23:12:38.000Z",
    "channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
    "title": "Google I/O 101: Q&A On Using Google APIs",
    "description": "Antonio Fuentes speaks to us and takes questions on working with Google APIs and OAuth 2.0.",
    "thumbnails": {
    "default": {
    "url": "https://i.ytimg.com/vi/7lCDEYXw3mM/default.jpg",
    "width": 120,
    "height": 90
    },
    "medium": {
    "url": "https://i.ytimg.com/vi/7lCDEYXw3mM/mqdefault.jpg",
    "width": 320,
    "height": 180
    },
    "high": {
    "url": "https://i.ytimg.com/vi/7lCDEYXw3mM/hqdefault.jpg",
    "width": 480,
    "height": 360
    }


    But now I want to parse it and get just 3 nodes:




    1. Title

    2. Description

    3. The url for the default thumbnail


    Indeed I get the Json response and can see it on the logs, but when try to parse it every time it fails.



    This is my code:



    final response = await http.get(
    'https://www.googleapis.com/youtube/v3/videos?id=HEREGOESMYAPIKEY&part=snippet&id=T0Jqdjbed40');

    final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
    String title = parsed['items']['snippet']['title'];
    print(title);
    String description = parsed['items']['snippet']['description'];
    print(description);
    String thumbnail = parsed['items']['snippet']['thumbnails']['default']['url'];
    print(thumbnail);









    share|improve this question



























      0












      0








      0


      1





      I make a call to Youtube API and get this Json:



           "kind": "youtube#videoListResponse",
      "etag": ""XI7nbFXulYBIpL0ayR_gDh3eu1k/s7-xmHXpuqQxYzDp_wxhm59K4LE"",
      "pageInfo": {
      "totalResults": 1,
      "resultsPerPage": 1
      },
      "items": [
      {
      "kind": "youtube#video",
      "etag": ""XI7nbFXulYBIpL0ayR_gDh3eu1k/pajQ7iBy-7A0V_owifxkw-Kbw-Y"",
      "id": "7lCDEYXw3mM",
      "snippet": {
      "publishedAt": "2012-06-20T23:12:38.000Z",
      "channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
      "title": "Google I/O 101: Q&A On Using Google APIs",
      "description": "Antonio Fuentes speaks to us and takes questions on working with Google APIs and OAuth 2.0.",
      "thumbnails": {
      "default": {
      "url": "https://i.ytimg.com/vi/7lCDEYXw3mM/default.jpg",
      "width": 120,
      "height": 90
      },
      "medium": {
      "url": "https://i.ytimg.com/vi/7lCDEYXw3mM/mqdefault.jpg",
      "width": 320,
      "height": 180
      },
      "high": {
      "url": "https://i.ytimg.com/vi/7lCDEYXw3mM/hqdefault.jpg",
      "width": 480,
      "height": 360
      }


      But now I want to parse it and get just 3 nodes:




      1. Title

      2. Description

      3. The url for the default thumbnail


      Indeed I get the Json response and can see it on the logs, but when try to parse it every time it fails.



      This is my code:



      final response = await http.get(
      'https://www.googleapis.com/youtube/v3/videos?id=HEREGOESMYAPIKEY&part=snippet&id=T0Jqdjbed40');

      final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
      String title = parsed['items']['snippet']['title'];
      print(title);
      String description = parsed['items']['snippet']['description'];
      print(description);
      String thumbnail = parsed['items']['snippet']['thumbnails']['default']['url'];
      print(thumbnail);









      share|improve this question















      I make a call to Youtube API and get this Json:



           "kind": "youtube#videoListResponse",
      "etag": ""XI7nbFXulYBIpL0ayR_gDh3eu1k/s7-xmHXpuqQxYzDp_wxhm59K4LE"",
      "pageInfo": {
      "totalResults": 1,
      "resultsPerPage": 1
      },
      "items": [
      {
      "kind": "youtube#video",
      "etag": ""XI7nbFXulYBIpL0ayR_gDh3eu1k/pajQ7iBy-7A0V_owifxkw-Kbw-Y"",
      "id": "7lCDEYXw3mM",
      "snippet": {
      "publishedAt": "2012-06-20T23:12:38.000Z",
      "channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
      "title": "Google I/O 101: Q&A On Using Google APIs",
      "description": "Antonio Fuentes speaks to us and takes questions on working with Google APIs and OAuth 2.0.",
      "thumbnails": {
      "default": {
      "url": "https://i.ytimg.com/vi/7lCDEYXw3mM/default.jpg",
      "width": 120,
      "height": 90
      },
      "medium": {
      "url": "https://i.ytimg.com/vi/7lCDEYXw3mM/mqdefault.jpg",
      "width": 320,
      "height": 180
      },
      "high": {
      "url": "https://i.ytimg.com/vi/7lCDEYXw3mM/hqdefault.jpg",
      "width": 480,
      "height": 360
      }


      But now I want to parse it and get just 3 nodes:




      1. Title

      2. Description

      3. The url for the default thumbnail


      Indeed I get the Json response and can see it on the logs, but when try to parse it every time it fails.



      This is my code:



      final response = await http.get(
      'https://www.googleapis.com/youtube/v3/videos?id=HEREGOESMYAPIKEY&part=snippet&id=T0Jqdjbed40');

      final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
      String title = parsed['items']['snippet']['title'];
      print(title);
      String description = parsed['items']['snippet']['description'];
      print(description);
      String thumbnail = parsed['items']['snippet']['thumbnails']['default']['url'];
      print(thumbnail);






      json flutter youtube-data-api






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 11 at 21:05

























      asked Nov 11 at 20:57









      Capitan Luzzatto

      36




      36
























          2 Answers
          2






          active

          oldest

          votes


















          2














          What you are trying won't work with Dart, this is not javascript. Dart has very strong type system, which is great. You are trying to assign value to a variable you've defined as String, but the response you have defined a dynamic, so Dart can't validate the value assignment. Also items is array, there is no such key items->snippet.



          The correct way to do this is to create model deinitions, which will handle deserialisation and also will provide convenient way of accessing properties you are interested in.



          class YoutubeResponse {

          String kind;
          String etag;
          String nextPageToken;

          String regionCode;
          List<Item> items;

          YoutubeResponse(
          {this.kind,
          this.etag,
          this.nextPageToken,
          this.regionCode,
          this.items});

          Map<String, dynamic> toJson() => {
          'kind': kind,
          'etag': etag,
          'nextPageToken': nextPageToken,
          'regionCode': regionCode,
          'items': items,
          };

          factory YoutubeResponse.fromJSON(Map<String, dynamic> YoutubeResponseJson) {

          var list = YoutubeResponseJson['items'] as List;
          List<Item> itemsList = list.map((i) => Item.fromJSON(i)).toList();

          return new YoutubeResponse(
          kind: YoutubeResponseJson['kind'],
          etag: YoutubeResponseJson['etag'],
          nextPageToken: YoutubeResponseJson['nextPageToken'],
          regionCode: YoutubeResponseJson['regionCode'],
          mPageInfo: pageInfo.fromJSON(YoutubeResponseJson['pageInfo']),
          items: itemsList);
          }

          }

          class Item {
          String kind;
          String etag;
          Id id;
          Snippet snippet;

          Item({this.kind, this.etag, this.id, this.snippet});

          Map<String, dynamic> toJson() => {
          'kind': kind,
          'etag': etag,
          'id': id,
          'snippet': snippet,
          };

          factory Item.fromJSON(Map<String, dynamic> ItemJson) {
          return Item(
          kind: ItemJson['kind'],
          etag: ItemJson['etag'],
          id: Id.fromJSON(ItemJson['id']),
          snippet: Snippet.fromJSON(ItemJson['snippet']),
          );
          }
          }

          class Snippet {
          String publishedAt;
          String channelId;
          String title;
          String description;
          Thumbnails thumbnails;
          String channelTitle;
          String liveBroadcastContent;

          Snippet(
          {this.publishedAt,
          this.channelId,
          this.title,
          this.description,
          this.thumbnails,
          this.channelTitle,
          this.liveBroadcastContent});


          Map<String, dynamic> toJson() => {
          'publishedAt': publishedAt,
          'channelId': channelId,
          'title': title,
          'description': description,
          'thumbnails': thumbnails,
          'channelTitle': channelTitle,
          'liveBroadcastContent': liveBroadcastContent,
          };

          factory Snippet.fromJSON(Map<String, dynamic> SnippetJson) {


          return Snippet(
          publishedAt: SnippetJson['publishedAt'],
          channelId: SnippetJson['channelId'],
          title: SnippetJson['title'],
          description: SnippetJson['description'],
          thumbnails: Thumbnails.fromJSON(SnippetJson['thumbnails']) ,
          channelTitle: SnippetJson['channelTitle'],
          liveBroadcastContent: SnippetJson['liveBroadcastContent'],
          );
          }
          }

          class Medium {
          int height;
          int width;
          String url;

          Medium({this.height, this.width, this.url});

          Map<String, dynamic> toJson() => {
          'height': height,
          'width': width,
          'url': url,
          };

          factory Medium.fromJSON(Map<String, dynamic> MediumJson) {
          return Medium(
          height: MediumJson['height'],
          width: MediumJson['width'],
          url: MediumJson['url'],
          );
          }

          }

          class High {
          int height;
          int width;
          String url;

          High({this.height, this.width, this.url});

          Map<String, dynamic> toJson() => {
          'height': height,
          'width': width,
          'url': url,
          };

          factory High.fromJSON(Map<String, dynamic> HighJson) {
          return High(
          height: HighJson['height'],
          width: HighJson['width'],
          url: HighJson['url'],
          );
          }

          }

          class Default {
          int height;
          int width;
          String url;

          Default({this.height, this.width, this.url});

          Map<String, dynamic> toJson() => {
          'height': height,
          'width': width,
          'url': url,
          };

          factory Default.fromJSON(Map<String, dynamic> defaultJson) {
          return Default(
          height: defaultJson['height'],
          width: defaultJson['width'],
          url: defaultJson['url'],
          );
          }

          }

          class Thumbnails {
          Default mDefault;
          Medium medium;
          High high;

          Thumbnails({this.mDefault, this.medium, this.high});

          var data = JsonEncoder().convert("");

          Map<String, dynamic> toJson() => {
          'default': mDefault,
          'medium': medium,
          'high': high,
          };

          factory Thumbnails.fromJSON(Map<String, dynamic> ThumbnailsJson) {
          return Thumbnails(
          mDefault: Default.fromJSON(ThumbnailsJson['default']),
          medium: Medium.fromJSON(ThumbnailsJson['medium']),
          high: High.fromJSON(ThumbnailsJson['high']),
          );
          }
          }


          Now that we have described the format of the JSON we expect it is very easy to parse it:



          YoutubeResponse parsedResponse =
          YoutubeResponse.fromJSON(json.decode(response.body));


          You can then access the items via parsedResponse.items, then loop through them and get the title, descriptions etc.






          share|improve this answer





















          • I added your code but it gives me a [VERBOSE-2:shell.cc(188)] Dart Error: Unhandled exception: NoSuchMethodError: The method 'fromJSON' was called on null.
            – Capitan Luzzatto
            Nov 11 at 23:25










          • @CapitanLuzzatto Have you created and imported all models?
            – shaddy
            Nov 12 at 4:27










          • Yes, also I noted that Android Studio didn't recognized the field Id on the Item object and mPageInfo ond YouTubeResponse object.
            – Capitan Luzzatto
            Nov 12 at 14:10



















          0














          To further the answer by @Shaddy (which works) here is my class that calls the network



              class VideoNetwork {
          static Future<List<Item>> fetchPost() async {
          final response =
          await http.get(<URL for Youtube Videos>);

          if (response.statusCode == 200) {
          // If the call to the server was successful, parse the JSON
          return compute(parseVideos, response.body);
          } else {
          // If that call was not successful, throw an error.
          throw Exception('Failed to load post');
          }
          }

          static List<Item> parseVideos(String responseBody) {
          YoutubeResponse response =
          YoutubeResponse.fromJSON(json.decode(responseBody));

          return response.items.toList();
          }
          }





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253169%2fdecode-json-from-youtube-api-on-flutter%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            What you are trying won't work with Dart, this is not javascript. Dart has very strong type system, which is great. You are trying to assign value to a variable you've defined as String, but the response you have defined a dynamic, so Dart can't validate the value assignment. Also items is array, there is no such key items->snippet.



            The correct way to do this is to create model deinitions, which will handle deserialisation and also will provide convenient way of accessing properties you are interested in.



            class YoutubeResponse {

            String kind;
            String etag;
            String nextPageToken;

            String regionCode;
            List<Item> items;

            YoutubeResponse(
            {this.kind,
            this.etag,
            this.nextPageToken,
            this.regionCode,
            this.items});

            Map<String, dynamic> toJson() => {
            'kind': kind,
            'etag': etag,
            'nextPageToken': nextPageToken,
            'regionCode': regionCode,
            'items': items,
            };

            factory YoutubeResponse.fromJSON(Map<String, dynamic> YoutubeResponseJson) {

            var list = YoutubeResponseJson['items'] as List;
            List<Item> itemsList = list.map((i) => Item.fromJSON(i)).toList();

            return new YoutubeResponse(
            kind: YoutubeResponseJson['kind'],
            etag: YoutubeResponseJson['etag'],
            nextPageToken: YoutubeResponseJson['nextPageToken'],
            regionCode: YoutubeResponseJson['regionCode'],
            mPageInfo: pageInfo.fromJSON(YoutubeResponseJson['pageInfo']),
            items: itemsList);
            }

            }

            class Item {
            String kind;
            String etag;
            Id id;
            Snippet snippet;

            Item({this.kind, this.etag, this.id, this.snippet});

            Map<String, dynamic> toJson() => {
            'kind': kind,
            'etag': etag,
            'id': id,
            'snippet': snippet,
            };

            factory Item.fromJSON(Map<String, dynamic> ItemJson) {
            return Item(
            kind: ItemJson['kind'],
            etag: ItemJson['etag'],
            id: Id.fromJSON(ItemJson['id']),
            snippet: Snippet.fromJSON(ItemJson['snippet']),
            );
            }
            }

            class Snippet {
            String publishedAt;
            String channelId;
            String title;
            String description;
            Thumbnails thumbnails;
            String channelTitle;
            String liveBroadcastContent;

            Snippet(
            {this.publishedAt,
            this.channelId,
            this.title,
            this.description,
            this.thumbnails,
            this.channelTitle,
            this.liveBroadcastContent});


            Map<String, dynamic> toJson() => {
            'publishedAt': publishedAt,
            'channelId': channelId,
            'title': title,
            'description': description,
            'thumbnails': thumbnails,
            'channelTitle': channelTitle,
            'liveBroadcastContent': liveBroadcastContent,
            };

            factory Snippet.fromJSON(Map<String, dynamic> SnippetJson) {


            return Snippet(
            publishedAt: SnippetJson['publishedAt'],
            channelId: SnippetJson['channelId'],
            title: SnippetJson['title'],
            description: SnippetJson['description'],
            thumbnails: Thumbnails.fromJSON(SnippetJson['thumbnails']) ,
            channelTitle: SnippetJson['channelTitle'],
            liveBroadcastContent: SnippetJson['liveBroadcastContent'],
            );
            }
            }

            class Medium {
            int height;
            int width;
            String url;

            Medium({this.height, this.width, this.url});

            Map<String, dynamic> toJson() => {
            'height': height,
            'width': width,
            'url': url,
            };

            factory Medium.fromJSON(Map<String, dynamic> MediumJson) {
            return Medium(
            height: MediumJson['height'],
            width: MediumJson['width'],
            url: MediumJson['url'],
            );
            }

            }

            class High {
            int height;
            int width;
            String url;

            High({this.height, this.width, this.url});

            Map<String, dynamic> toJson() => {
            'height': height,
            'width': width,
            'url': url,
            };

            factory High.fromJSON(Map<String, dynamic> HighJson) {
            return High(
            height: HighJson['height'],
            width: HighJson['width'],
            url: HighJson['url'],
            );
            }

            }

            class Default {
            int height;
            int width;
            String url;

            Default({this.height, this.width, this.url});

            Map<String, dynamic> toJson() => {
            'height': height,
            'width': width,
            'url': url,
            };

            factory Default.fromJSON(Map<String, dynamic> defaultJson) {
            return Default(
            height: defaultJson['height'],
            width: defaultJson['width'],
            url: defaultJson['url'],
            );
            }

            }

            class Thumbnails {
            Default mDefault;
            Medium medium;
            High high;

            Thumbnails({this.mDefault, this.medium, this.high});

            var data = JsonEncoder().convert("");

            Map<String, dynamic> toJson() => {
            'default': mDefault,
            'medium': medium,
            'high': high,
            };

            factory Thumbnails.fromJSON(Map<String, dynamic> ThumbnailsJson) {
            return Thumbnails(
            mDefault: Default.fromJSON(ThumbnailsJson['default']),
            medium: Medium.fromJSON(ThumbnailsJson['medium']),
            high: High.fromJSON(ThumbnailsJson['high']),
            );
            }
            }


            Now that we have described the format of the JSON we expect it is very easy to parse it:



            YoutubeResponse parsedResponse =
            YoutubeResponse.fromJSON(json.decode(response.body));


            You can then access the items via parsedResponse.items, then loop through them and get the title, descriptions etc.






            share|improve this answer





















            • I added your code but it gives me a [VERBOSE-2:shell.cc(188)] Dart Error: Unhandled exception: NoSuchMethodError: The method 'fromJSON' was called on null.
              – Capitan Luzzatto
              Nov 11 at 23:25










            • @CapitanLuzzatto Have you created and imported all models?
              – shaddy
              Nov 12 at 4:27










            • Yes, also I noted that Android Studio didn't recognized the field Id on the Item object and mPageInfo ond YouTubeResponse object.
              – Capitan Luzzatto
              Nov 12 at 14:10
















            2














            What you are trying won't work with Dart, this is not javascript. Dart has very strong type system, which is great. You are trying to assign value to a variable you've defined as String, but the response you have defined a dynamic, so Dart can't validate the value assignment. Also items is array, there is no such key items->snippet.



            The correct way to do this is to create model deinitions, which will handle deserialisation and also will provide convenient way of accessing properties you are interested in.



            class YoutubeResponse {

            String kind;
            String etag;
            String nextPageToken;

            String regionCode;
            List<Item> items;

            YoutubeResponse(
            {this.kind,
            this.etag,
            this.nextPageToken,
            this.regionCode,
            this.items});

            Map<String, dynamic> toJson() => {
            'kind': kind,
            'etag': etag,
            'nextPageToken': nextPageToken,
            'regionCode': regionCode,
            'items': items,
            };

            factory YoutubeResponse.fromJSON(Map<String, dynamic> YoutubeResponseJson) {

            var list = YoutubeResponseJson['items'] as List;
            List<Item> itemsList = list.map((i) => Item.fromJSON(i)).toList();

            return new YoutubeResponse(
            kind: YoutubeResponseJson['kind'],
            etag: YoutubeResponseJson['etag'],
            nextPageToken: YoutubeResponseJson['nextPageToken'],
            regionCode: YoutubeResponseJson['regionCode'],
            mPageInfo: pageInfo.fromJSON(YoutubeResponseJson['pageInfo']),
            items: itemsList);
            }

            }

            class Item {
            String kind;
            String etag;
            Id id;
            Snippet snippet;

            Item({this.kind, this.etag, this.id, this.snippet});

            Map<String, dynamic> toJson() => {
            'kind': kind,
            'etag': etag,
            'id': id,
            'snippet': snippet,
            };

            factory Item.fromJSON(Map<String, dynamic> ItemJson) {
            return Item(
            kind: ItemJson['kind'],
            etag: ItemJson['etag'],
            id: Id.fromJSON(ItemJson['id']),
            snippet: Snippet.fromJSON(ItemJson['snippet']),
            );
            }
            }

            class Snippet {
            String publishedAt;
            String channelId;
            String title;
            String description;
            Thumbnails thumbnails;
            String channelTitle;
            String liveBroadcastContent;

            Snippet(
            {this.publishedAt,
            this.channelId,
            this.title,
            this.description,
            this.thumbnails,
            this.channelTitle,
            this.liveBroadcastContent});


            Map<String, dynamic> toJson() => {
            'publishedAt': publishedAt,
            'channelId': channelId,
            'title': title,
            'description': description,
            'thumbnails': thumbnails,
            'channelTitle': channelTitle,
            'liveBroadcastContent': liveBroadcastContent,
            };

            factory Snippet.fromJSON(Map<String, dynamic> SnippetJson) {


            return Snippet(
            publishedAt: SnippetJson['publishedAt'],
            channelId: SnippetJson['channelId'],
            title: SnippetJson['title'],
            description: SnippetJson['description'],
            thumbnails: Thumbnails.fromJSON(SnippetJson['thumbnails']) ,
            channelTitle: SnippetJson['channelTitle'],
            liveBroadcastContent: SnippetJson['liveBroadcastContent'],
            );
            }
            }

            class Medium {
            int height;
            int width;
            String url;

            Medium({this.height, this.width, this.url});

            Map<String, dynamic> toJson() => {
            'height': height,
            'width': width,
            'url': url,
            };

            factory Medium.fromJSON(Map<String, dynamic> MediumJson) {
            return Medium(
            height: MediumJson['height'],
            width: MediumJson['width'],
            url: MediumJson['url'],
            );
            }

            }

            class High {
            int height;
            int width;
            String url;

            High({this.height, this.width, this.url});

            Map<String, dynamic> toJson() => {
            'height': height,
            'width': width,
            'url': url,
            };

            factory High.fromJSON(Map<String, dynamic> HighJson) {
            return High(
            height: HighJson['height'],
            width: HighJson['width'],
            url: HighJson['url'],
            );
            }

            }

            class Default {
            int height;
            int width;
            String url;

            Default({this.height, this.width, this.url});

            Map<String, dynamic> toJson() => {
            'height': height,
            'width': width,
            'url': url,
            };

            factory Default.fromJSON(Map<String, dynamic> defaultJson) {
            return Default(
            height: defaultJson['height'],
            width: defaultJson['width'],
            url: defaultJson['url'],
            );
            }

            }

            class Thumbnails {
            Default mDefault;
            Medium medium;
            High high;

            Thumbnails({this.mDefault, this.medium, this.high});

            var data = JsonEncoder().convert("");

            Map<String, dynamic> toJson() => {
            'default': mDefault,
            'medium': medium,
            'high': high,
            };

            factory Thumbnails.fromJSON(Map<String, dynamic> ThumbnailsJson) {
            return Thumbnails(
            mDefault: Default.fromJSON(ThumbnailsJson['default']),
            medium: Medium.fromJSON(ThumbnailsJson['medium']),
            high: High.fromJSON(ThumbnailsJson['high']),
            );
            }
            }


            Now that we have described the format of the JSON we expect it is very easy to parse it:



            YoutubeResponse parsedResponse =
            YoutubeResponse.fromJSON(json.decode(response.body));


            You can then access the items via parsedResponse.items, then loop through them and get the title, descriptions etc.






            share|improve this answer





















            • I added your code but it gives me a [VERBOSE-2:shell.cc(188)] Dart Error: Unhandled exception: NoSuchMethodError: The method 'fromJSON' was called on null.
              – Capitan Luzzatto
              Nov 11 at 23:25










            • @CapitanLuzzatto Have you created and imported all models?
              – shaddy
              Nov 12 at 4:27










            • Yes, also I noted that Android Studio didn't recognized the field Id on the Item object and mPageInfo ond YouTubeResponse object.
              – Capitan Luzzatto
              Nov 12 at 14:10














            2












            2








            2






            What you are trying won't work with Dart, this is not javascript. Dart has very strong type system, which is great. You are trying to assign value to a variable you've defined as String, but the response you have defined a dynamic, so Dart can't validate the value assignment. Also items is array, there is no such key items->snippet.



            The correct way to do this is to create model deinitions, which will handle deserialisation and also will provide convenient way of accessing properties you are interested in.



            class YoutubeResponse {

            String kind;
            String etag;
            String nextPageToken;

            String regionCode;
            List<Item> items;

            YoutubeResponse(
            {this.kind,
            this.etag,
            this.nextPageToken,
            this.regionCode,
            this.items});

            Map<String, dynamic> toJson() => {
            'kind': kind,
            'etag': etag,
            'nextPageToken': nextPageToken,
            'regionCode': regionCode,
            'items': items,
            };

            factory YoutubeResponse.fromJSON(Map<String, dynamic> YoutubeResponseJson) {

            var list = YoutubeResponseJson['items'] as List;
            List<Item> itemsList = list.map((i) => Item.fromJSON(i)).toList();

            return new YoutubeResponse(
            kind: YoutubeResponseJson['kind'],
            etag: YoutubeResponseJson['etag'],
            nextPageToken: YoutubeResponseJson['nextPageToken'],
            regionCode: YoutubeResponseJson['regionCode'],
            mPageInfo: pageInfo.fromJSON(YoutubeResponseJson['pageInfo']),
            items: itemsList);
            }

            }

            class Item {
            String kind;
            String etag;
            Id id;
            Snippet snippet;

            Item({this.kind, this.etag, this.id, this.snippet});

            Map<String, dynamic> toJson() => {
            'kind': kind,
            'etag': etag,
            'id': id,
            'snippet': snippet,
            };

            factory Item.fromJSON(Map<String, dynamic> ItemJson) {
            return Item(
            kind: ItemJson['kind'],
            etag: ItemJson['etag'],
            id: Id.fromJSON(ItemJson['id']),
            snippet: Snippet.fromJSON(ItemJson['snippet']),
            );
            }
            }

            class Snippet {
            String publishedAt;
            String channelId;
            String title;
            String description;
            Thumbnails thumbnails;
            String channelTitle;
            String liveBroadcastContent;

            Snippet(
            {this.publishedAt,
            this.channelId,
            this.title,
            this.description,
            this.thumbnails,
            this.channelTitle,
            this.liveBroadcastContent});


            Map<String, dynamic> toJson() => {
            'publishedAt': publishedAt,
            'channelId': channelId,
            'title': title,
            'description': description,
            'thumbnails': thumbnails,
            'channelTitle': channelTitle,
            'liveBroadcastContent': liveBroadcastContent,
            };

            factory Snippet.fromJSON(Map<String, dynamic> SnippetJson) {


            return Snippet(
            publishedAt: SnippetJson['publishedAt'],
            channelId: SnippetJson['channelId'],
            title: SnippetJson['title'],
            description: SnippetJson['description'],
            thumbnails: Thumbnails.fromJSON(SnippetJson['thumbnails']) ,
            channelTitle: SnippetJson['channelTitle'],
            liveBroadcastContent: SnippetJson['liveBroadcastContent'],
            );
            }
            }

            class Medium {
            int height;
            int width;
            String url;

            Medium({this.height, this.width, this.url});

            Map<String, dynamic> toJson() => {
            'height': height,
            'width': width,
            'url': url,
            };

            factory Medium.fromJSON(Map<String, dynamic> MediumJson) {
            return Medium(
            height: MediumJson['height'],
            width: MediumJson['width'],
            url: MediumJson['url'],
            );
            }

            }

            class High {
            int height;
            int width;
            String url;

            High({this.height, this.width, this.url});

            Map<String, dynamic> toJson() => {
            'height': height,
            'width': width,
            'url': url,
            };

            factory High.fromJSON(Map<String, dynamic> HighJson) {
            return High(
            height: HighJson['height'],
            width: HighJson['width'],
            url: HighJson['url'],
            );
            }

            }

            class Default {
            int height;
            int width;
            String url;

            Default({this.height, this.width, this.url});

            Map<String, dynamic> toJson() => {
            'height': height,
            'width': width,
            'url': url,
            };

            factory Default.fromJSON(Map<String, dynamic> defaultJson) {
            return Default(
            height: defaultJson['height'],
            width: defaultJson['width'],
            url: defaultJson['url'],
            );
            }

            }

            class Thumbnails {
            Default mDefault;
            Medium medium;
            High high;

            Thumbnails({this.mDefault, this.medium, this.high});

            var data = JsonEncoder().convert("");

            Map<String, dynamic> toJson() => {
            'default': mDefault,
            'medium': medium,
            'high': high,
            };

            factory Thumbnails.fromJSON(Map<String, dynamic> ThumbnailsJson) {
            return Thumbnails(
            mDefault: Default.fromJSON(ThumbnailsJson['default']),
            medium: Medium.fromJSON(ThumbnailsJson['medium']),
            high: High.fromJSON(ThumbnailsJson['high']),
            );
            }
            }


            Now that we have described the format of the JSON we expect it is very easy to parse it:



            YoutubeResponse parsedResponse =
            YoutubeResponse.fromJSON(json.decode(response.body));


            You can then access the items via parsedResponse.items, then loop through them and get the title, descriptions etc.






            share|improve this answer












            What you are trying won't work with Dart, this is not javascript. Dart has very strong type system, which is great. You are trying to assign value to a variable you've defined as String, but the response you have defined a dynamic, so Dart can't validate the value assignment. Also items is array, there is no such key items->snippet.



            The correct way to do this is to create model deinitions, which will handle deserialisation and also will provide convenient way of accessing properties you are interested in.



            class YoutubeResponse {

            String kind;
            String etag;
            String nextPageToken;

            String regionCode;
            List<Item> items;

            YoutubeResponse(
            {this.kind,
            this.etag,
            this.nextPageToken,
            this.regionCode,
            this.items});

            Map<String, dynamic> toJson() => {
            'kind': kind,
            'etag': etag,
            'nextPageToken': nextPageToken,
            'regionCode': regionCode,
            'items': items,
            };

            factory YoutubeResponse.fromJSON(Map<String, dynamic> YoutubeResponseJson) {

            var list = YoutubeResponseJson['items'] as List;
            List<Item> itemsList = list.map((i) => Item.fromJSON(i)).toList();

            return new YoutubeResponse(
            kind: YoutubeResponseJson['kind'],
            etag: YoutubeResponseJson['etag'],
            nextPageToken: YoutubeResponseJson['nextPageToken'],
            regionCode: YoutubeResponseJson['regionCode'],
            mPageInfo: pageInfo.fromJSON(YoutubeResponseJson['pageInfo']),
            items: itemsList);
            }

            }

            class Item {
            String kind;
            String etag;
            Id id;
            Snippet snippet;

            Item({this.kind, this.etag, this.id, this.snippet});

            Map<String, dynamic> toJson() => {
            'kind': kind,
            'etag': etag,
            'id': id,
            'snippet': snippet,
            };

            factory Item.fromJSON(Map<String, dynamic> ItemJson) {
            return Item(
            kind: ItemJson['kind'],
            etag: ItemJson['etag'],
            id: Id.fromJSON(ItemJson['id']),
            snippet: Snippet.fromJSON(ItemJson['snippet']),
            );
            }
            }

            class Snippet {
            String publishedAt;
            String channelId;
            String title;
            String description;
            Thumbnails thumbnails;
            String channelTitle;
            String liveBroadcastContent;

            Snippet(
            {this.publishedAt,
            this.channelId,
            this.title,
            this.description,
            this.thumbnails,
            this.channelTitle,
            this.liveBroadcastContent});


            Map<String, dynamic> toJson() => {
            'publishedAt': publishedAt,
            'channelId': channelId,
            'title': title,
            'description': description,
            'thumbnails': thumbnails,
            'channelTitle': channelTitle,
            'liveBroadcastContent': liveBroadcastContent,
            };

            factory Snippet.fromJSON(Map<String, dynamic> SnippetJson) {


            return Snippet(
            publishedAt: SnippetJson['publishedAt'],
            channelId: SnippetJson['channelId'],
            title: SnippetJson['title'],
            description: SnippetJson['description'],
            thumbnails: Thumbnails.fromJSON(SnippetJson['thumbnails']) ,
            channelTitle: SnippetJson['channelTitle'],
            liveBroadcastContent: SnippetJson['liveBroadcastContent'],
            );
            }
            }

            class Medium {
            int height;
            int width;
            String url;

            Medium({this.height, this.width, this.url});

            Map<String, dynamic> toJson() => {
            'height': height,
            'width': width,
            'url': url,
            };

            factory Medium.fromJSON(Map<String, dynamic> MediumJson) {
            return Medium(
            height: MediumJson['height'],
            width: MediumJson['width'],
            url: MediumJson['url'],
            );
            }

            }

            class High {
            int height;
            int width;
            String url;

            High({this.height, this.width, this.url});

            Map<String, dynamic> toJson() => {
            'height': height,
            'width': width,
            'url': url,
            };

            factory High.fromJSON(Map<String, dynamic> HighJson) {
            return High(
            height: HighJson['height'],
            width: HighJson['width'],
            url: HighJson['url'],
            );
            }

            }

            class Default {
            int height;
            int width;
            String url;

            Default({this.height, this.width, this.url});

            Map<String, dynamic> toJson() => {
            'height': height,
            'width': width,
            'url': url,
            };

            factory Default.fromJSON(Map<String, dynamic> defaultJson) {
            return Default(
            height: defaultJson['height'],
            width: defaultJson['width'],
            url: defaultJson['url'],
            );
            }

            }

            class Thumbnails {
            Default mDefault;
            Medium medium;
            High high;

            Thumbnails({this.mDefault, this.medium, this.high});

            var data = JsonEncoder().convert("");

            Map<String, dynamic> toJson() => {
            'default': mDefault,
            'medium': medium,
            'high': high,
            };

            factory Thumbnails.fromJSON(Map<String, dynamic> ThumbnailsJson) {
            return Thumbnails(
            mDefault: Default.fromJSON(ThumbnailsJson['default']),
            medium: Medium.fromJSON(ThumbnailsJson['medium']),
            high: High.fromJSON(ThumbnailsJson['high']),
            );
            }
            }


            Now that we have described the format of the JSON we expect it is very easy to parse it:



            YoutubeResponse parsedResponse =
            YoutubeResponse.fromJSON(json.decode(response.body));


            You can then access the items via parsedResponse.items, then loop through them and get the title, descriptions etc.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 11 at 21:36









            shaddy

            6,16331631




            6,16331631












            • I added your code but it gives me a [VERBOSE-2:shell.cc(188)] Dart Error: Unhandled exception: NoSuchMethodError: The method 'fromJSON' was called on null.
              – Capitan Luzzatto
              Nov 11 at 23:25










            • @CapitanLuzzatto Have you created and imported all models?
              – shaddy
              Nov 12 at 4:27










            • Yes, also I noted that Android Studio didn't recognized the field Id on the Item object and mPageInfo ond YouTubeResponse object.
              – Capitan Luzzatto
              Nov 12 at 14:10


















            • I added your code but it gives me a [VERBOSE-2:shell.cc(188)] Dart Error: Unhandled exception: NoSuchMethodError: The method 'fromJSON' was called on null.
              – Capitan Luzzatto
              Nov 11 at 23:25










            • @CapitanLuzzatto Have you created and imported all models?
              – shaddy
              Nov 12 at 4:27










            • Yes, also I noted that Android Studio didn't recognized the field Id on the Item object and mPageInfo ond YouTubeResponse object.
              – Capitan Luzzatto
              Nov 12 at 14:10
















            I added your code but it gives me a [VERBOSE-2:shell.cc(188)] Dart Error: Unhandled exception: NoSuchMethodError: The method 'fromJSON' was called on null.
            – Capitan Luzzatto
            Nov 11 at 23:25




            I added your code but it gives me a [VERBOSE-2:shell.cc(188)] Dart Error: Unhandled exception: NoSuchMethodError: The method 'fromJSON' was called on null.
            – Capitan Luzzatto
            Nov 11 at 23:25












            @CapitanLuzzatto Have you created and imported all models?
            – shaddy
            Nov 12 at 4:27




            @CapitanLuzzatto Have you created and imported all models?
            – shaddy
            Nov 12 at 4:27












            Yes, also I noted that Android Studio didn't recognized the field Id on the Item object and mPageInfo ond YouTubeResponse object.
            – Capitan Luzzatto
            Nov 12 at 14:10




            Yes, also I noted that Android Studio didn't recognized the field Id on the Item object and mPageInfo ond YouTubeResponse object.
            – Capitan Luzzatto
            Nov 12 at 14:10













            0














            To further the answer by @Shaddy (which works) here is my class that calls the network



                class VideoNetwork {
            static Future<List<Item>> fetchPost() async {
            final response =
            await http.get(<URL for Youtube Videos>);

            if (response.statusCode == 200) {
            // If the call to the server was successful, parse the JSON
            return compute(parseVideos, response.body);
            } else {
            // If that call was not successful, throw an error.
            throw Exception('Failed to load post');
            }
            }

            static List<Item> parseVideos(String responseBody) {
            YoutubeResponse response =
            YoutubeResponse.fromJSON(json.decode(responseBody));

            return response.items.toList();
            }
            }





            share|improve this answer


























              0














              To further the answer by @Shaddy (which works) here is my class that calls the network



                  class VideoNetwork {
              static Future<List<Item>> fetchPost() async {
              final response =
              await http.get(<URL for Youtube Videos>);

              if (response.statusCode == 200) {
              // If the call to the server was successful, parse the JSON
              return compute(parseVideos, response.body);
              } else {
              // If that call was not successful, throw an error.
              throw Exception('Failed to load post');
              }
              }

              static List<Item> parseVideos(String responseBody) {
              YoutubeResponse response =
              YoutubeResponse.fromJSON(json.decode(responseBody));

              return response.items.toList();
              }
              }





              share|improve this answer
























                0












                0








                0






                To further the answer by @Shaddy (which works) here is my class that calls the network



                    class VideoNetwork {
                static Future<List<Item>> fetchPost() async {
                final response =
                await http.get(<URL for Youtube Videos>);

                if (response.statusCode == 200) {
                // If the call to the server was successful, parse the JSON
                return compute(parseVideos, response.body);
                } else {
                // If that call was not successful, throw an error.
                throw Exception('Failed to load post');
                }
                }

                static List<Item> parseVideos(String responseBody) {
                YoutubeResponse response =
                YoutubeResponse.fromJSON(json.decode(responseBody));

                return response.items.toList();
                }
                }





                share|improve this answer












                To further the answer by @Shaddy (which works) here is my class that calls the network



                    class VideoNetwork {
                static Future<List<Item>> fetchPost() async {
                final response =
                await http.get(<URL for Youtube Videos>);

                if (response.statusCode == 200) {
                // If the call to the server was successful, parse the JSON
                return compute(parseVideos, response.body);
                } else {
                // If that call was not successful, throw an error.
                throw Exception('Failed to load post');
                }
                }

                static List<Item> parseVideos(String responseBody) {
                YoutubeResponse response =
                YoutubeResponse.fromJSON(json.decode(responseBody));

                return response.items.toList();
                }
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 26 at 6:00









                mossman252

                27623




                27623






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253169%2fdecode-json-from-youtube-api-on-flutter%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Tangent Lines Diagram Along Smooth Curve

                    Yusuf al-Mu'taman ibn Hud

                    Zucchini