【问题标题】:How can I parse nested JSON using Flutter?如何使用 Flutter 解析嵌套的 JSON?
【发布时间】:2020-09-24 15:42:17
【问题描述】:

我想解析这个 JSON 数据,但我不知道如何解析它。

{
    "kind": "Testing",
    "data": {
        "modhash": "fffffghhhhhhbf0bb4601d6158db548b5296632215a0",
        "dist": 75,
        "children": [
            {
                "kind": "z4",
                "data": {
                    "subreddit": "iOS",
                    "selftext": "I am iOS developer",
                    "author_fullname": "tyy_iif5q",
                    "saved": false,
                    "gilded": 0,
                    "clicked": false,
                    "title": "When is a good time to use docker?",
                    "subreddit_name_prefixed": "r/webdev",
                    "hidden": false,
                    "pwls": 6,
                    "downs": 0,
                    "hide_score": false,
                    "name": "t3_gwqan4",
                    "quarantine": false,
                    "link_flair_text_color": "dark",
                    "upvote_ratio": 0.96,
                    "subreddit_type": "public",
                    "ups": 277,
                    "total_awards_received": 0,
                    "is_original_content": false,
                    "is_reddit_media_domain": false,
                    "is_meta": false,
                    "can_mod_post": false,
                    "score": 277,
                    "author_premium": false,
                    "thumbnail": "self",
                    "edited": false,
                    "is_self": true,
                    "created": 1591333752,
                    "link_flair_type": "text",
                    "wls": 6,
                    "author_flair_type": "text",
                    "domain": "self.webdev",
                    "allow_live_comments": false,
                    "selftext_html": "<!-- SC_OFF --><div class=\"md\"><p>I just finished part 7 of the Full Stack Open course (<a href=\"https://www.fullstackopen.com/en\">www.fullstackopen.com/en</a>) and due to graphQL and typescript not being within the core content of the course, I thought I might try and learn docker. </p>\n\n<p>Turns out, trying to learn docker is just making me even more confused than when I didn't even know docker existed. </p>\n\n<p>​</p>\n\n<p>Could someone explain to me, when is a good time to use docker? How one would go about using docker, and when in someone's learning path would one ideally learn docker?</p>\n\n<p>​</p>\n\n<p>I am still learning react, databases, and overall front-end and back-end web development currently. The most I have done thus-far is hosting an app I made on heroku. I haven't setup a personal website, portfolio, or hosted an app on an independent website either.</p>\n</div><!-- SC_ON -->",
                    "archived": false,
                    "no_follow": false,
                    "is_crosspostable": true,
                    "pinned": false,
                    "over_18": false,
                    "media_only": false,
                    "can_gild": true,
                    "spoiler": false,
                    "locked": false,
                    "visited": false,
                    "subreddit_id": "t5_2qs0q",
                    "id": "gwqan4",
                    "is_robot_indexable": true,
                    "author": "Sensualities",
                    "num_comments": 127,
                    "send_replies": true,
                    "whitelist_status": "all_ads",
                    "contest_mode": false,
                    "author_patreon_flair": false,
                    "permalink": "/r/webdev/comments/gwqan4/when_is_a_good_time_to_use_docker/",
                    "parent_whitelist_status": "all_ads",
                    "stickied": false,
                    "url": "https://www.reddit.com/r/webdev/comments/gwqan4/when_is_a_good_time_to_use_docker/",
                    "subreddit_subscribers": 487697,
                    "created_utc": 1591304952,
                    "num_crossposts": 1,
                    "is_video": false
                }
            },
            {
                "kind": "t3",
                "data": {
                    "subreddit": "iOS",
                    "selftext": "I am iOS developer",
                    "author_fullname": "tyy_iif5q",
                    "saved": false,
                    "gilded": 0,
                    "clicked": false,
                    "title": "When is a good time to use docker?",
                    "subreddit_name_prefixed": "r/webdev",
                    "hidden": false,
                    "pwls": 6,
                    "downs": 0,
                    "hide_score": false,
                    "name": "t3_gwqan4",
                    "quarantine": false,
                    "link_flair_text_color": "dark",
                    "upvote_ratio": 0.96,
                    "subreddit_type": "public",
                    "ups": 277,
                    "total_awards_received": 0,
                    "is_original_content": false,
                    "is_reddit_media_domain": false,
                    "is_meta": false,
                    "can_mod_post": false,
                    "score": 277,
                    "author_premium": false,
                    "thumbnail": "self",
                    "edited": false,
                    "is_self": true,
                    "created": 1591333752,
                    "link_flair_type": "text",
                    "wls": 6,
                    "author_flair_type": "text",
                    "domain": "self.webdev",
                    "allow_live_comments": false,
                    "selftext_html": "<!-- SC_OFF --><div class=\"md\"><p>I just finished part 7 of the Full Stack Open course (<a href=\"https://www.fullstackopen.com/en\">www.fullstackopen.com/en</a>) and due to graphQL and typescript not being within the core content of the course, I thought I might try and learn docker. </p>\n\n<p>Turns out, trying to learn docker is just making me even more confused than when I didn't even know docker existed. </p>\n\n<p>​</p>\n\n<p>Could someone explain to me, when is a good time to use docker? How one would go about using docker, and when in someone's learning path would one ideally learn docker?</p>\n\n<p>​</p>\n\n<p>I am still learning react, databases, and overall front-end and back-end web development currently. The most I have done thus-far is hosting an app I made on heroku. I haven't setup a personal website, portfolio, or hosted an app on an independent website either.</p>\n</div><!-- SC_ON -->",
                    "archived": false,
                    "no_follow": false,
                    "is_crosspostable": true,
                    "pinned": false,
                    "over_18": false,
                    "media_only": false,
                    "can_gild": true,
                    "spoiler": false,
                    "locked": false,
                    "visited": false,
                    "subreddit_id": "t5_2qs0q",
                    "id": "gwqan4",
                    "is_robot_indexable": true,
                    "author": "Sensualities",
                    "num_comments": 127,
                    "send_replies": true,
                    "whitelist_status": "all_ads",
                    "contest_mode": false,
                    "author_patreon_flair": false,
                    "permalink": "/r/webdev/comments/gwqan4/when_is_a_good_time_to_use_docker/",
                    "parent_whitelist_status": "all_ads",
                    "stickied": false,
                    "url": "https://www.reddit.com/r/webdev/comments/gwqan4/when_is_a_good_time_to_use_docker/",
                    "subreddit_subscribers": 487697,
                    "created_utc": 1591304952,
                    "num_crossposts": 1,
                    "is_video": false
                }
            }
        ],
        "after": "ggggggg"
    }
}

我想解析这个 JSON 数据,但我不知道如何解析它。我使用简单的 json,但我不知道如何解析嵌套的 json,请帮助我。我想解析这个 JSON 数据,但我不知道如何解析它。我使用简单的 json,但我不知道如何解析嵌套的 json,请帮助我。

【问题讨论】:

  • 在提出这个问题之前,您是否查看了现有的答案和资源?
  • 为了让人们花时间在 Stackoverflow 上帮助您,您将不得不付出更多的努力。从搜索“flutter json”开始,如果您仍然遇到麻烦,那么来更新您的问题并准确说出您卡在哪里。如果您没有遇到困难,也许您可​​以来发布您自己问题的答案,以便下次有人遇到此问题时,他们可以找到您的解决方案。

标签: json flutter dart


【解决方案1】:

看看这个库,它会对你有所帮助;)

https://pub.dev/packages/json_serializable

这个库将为每个带有@JsonSerializable注释的模型生成fromJson和toJson的转换代码

它负责嵌套对象、类型转换和许多其他事情;)

【讨论】:

    【解决方案2】:

    使用此链接准备 Json 的模型类 https://javiercbk.github.io/json_to_dart/

    HttpResponse 响应 = callApi;

    然后在得到响应后使用 json.decode;

    然后使用通过链接生成的模型的 fromjson 方法并解析整个 json

    Map userMap = jsonDecode(jsonString);
    var user = User.fromJson(userMap);
    

    用户是从站点创建的模型

    【讨论】:

      【解决方案3】:

      首先,您需要一个表示 JSON 的类,该类使用 fromJson 方法将 JSON 解析为您的对象。

      您还应该为嵌套的 JSON 字段使用嵌套类

      或者,您可以使用this class generator 生成必要的类

      class JSONRepresentation {
        final String kind;
        final Data data;
        JSONRepresentation({this.kind, this.data});
        JSONRepresentation .fromJson(Map<String, dynamic> data)
            : kind = data['kind'],
              data = Data .fromJson(data['data']);
      }
      
      class Data {
        final String modhash;
        final int dist;
        //final List<AnotherDataClass> children;
        final String after;
      
        Data({this.modhash, this.dist, this.after});
        Data .fromJson(Map<String, dynamic> data)
            : modhash = data['modhash'],
              dist = data['dist'],
              after = data['after'];
      }
      

      然后您可以使用dart:convert 对其进行解析,并从代表 JSON 的对象中获取数据,如下所示

      import "dart:convert";
      
      void main() {
        var jsonData = 
          '{"kind": "Testing",
            "data": { 
               "modhash": "fffffghhhhhhbf0bb4601d6158db548b5296632215a0",
               "dist": 75, 
               //"children": [...],
               "after": "ggggggg"}}';
      
        var parsedJson = json.decode(jsonData);
        var jsonRepresentationObject = JSONRepresentation.fromJson(parsedJson);
      
        //Example of getting data from objects  representing JSON
        print("kind: "+ jsonRepresentationObject.kind +
              "\nData modhash: " + jsonRepresentationObject.data.modhash);
      }
      

      您可以测试我的示例 here - 在线 dart 编译器

      【讨论】:

        猜你喜欢
        • 2021-02-25
        • 2019-10-06
        • 2019-01-24
        • 2020-11-08
        • 2020-05-21
        • 2023-04-02
        • 2019-12-30
        • 2021-02-09
        • 2018-07-12
        相关资源
        最近更新 更多