首页 > 解决方案 > 如何将json解析为list而不是flutter中的map

问题描述

如何解析 JSON 以在 Flutter 中列出。我已经使用在线工具来解析 Json,但该工具正在将其转换为地图。我需要在列表中获取解析的 json 并在页面的 listview builder 中返回内容列表。我有我的 json 文件和下面的解决方法。

json

{
    "batchcomplete": "",
    "continue": {
        "gcmcontinue": "page|41434143494120464552525547494e4541202d204152494d45444148|3704",
        "continue": "gcmcontinue||"
    },
    "query": {
        "pages": {
            "225": {
                "pageid": 225,
                "ns": 0,
                "title": "Abrus precatorius - Gunja",
                "thumbnail": {
                    "source": "https://example.org/images/thumb/c/cb/Abrus_precatorius_%281463017430%29.jpg/600px-Abrus_precatorius_%281463017430%29.jpg",
                    "width": 600,
                    "height": 450
                },
                "pageimage": "Abrus_precatorius_(1463017430).jpg"
            },
            "625": {
                "pageid": 625,
                "ns": 0,
                "title": "Abies webbiana - Talispatra",
                "thumbnail": {
                    "source": "https://example.org/images/thumb/b/b1/Red_fir.jpg/397px-Red_fir.jpg",
                    "width": 397,
                    "height": 600
                },
                "pageimage": "Red_fir.jpg"
            },
            "15995": {
                "pageid": 15995,
                "ns": 0,
                "title": "Abelmoschus esculentus - Bhenda",
                "thumbnail": {
                    "source": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d0/India_-_Koyambedu_Market_-_Ladies_Finger_03_%283986242135%29.jpg/600px-India_-_Koyambedu_Market_-_Ladies_Finger_03_%283986242135%29.jpg",
                    "width": 600,
                    "height": 450
                },
                "pageimage": "India_-_Koyambedu_Market_-_Ladies_Finger_03_(3986242135).jpg"
            }
        }
    },
    "limits": {
        "pageimages": 500
    }
}

Herbslist.dart

class Herbs extends StatefulWidget {
  final String title;
  Herbs(this.title);

  @override
  _HerbsState createState() => new _HerbsState();
}

class _HerbsState extends State<Herbs> {
  var cname;

  Future<Herbslist> fetchPost() async {
    final response = await http.get(
        'https://example.org/api.php?action=query&gcmtitle=Category:$cname&pilimit=max&prop=pageimages&pithumbsize=600&generator=categorymembers&format=json&gcmcontinue='
        );
    if (response.statusCode == 200) {
      if(this.mounted){
      return Herbslist.fromJson(json.decode(response.body));
      }
    } else {
      print(Exception);
      throw (e) {
        print("Exception thrown: $e");
        Exception(e);
      };
    }
  }

  @override
  Widget build(BuildContext context) {
    cname = widget.title;
    return new Scaffold(
        appBar: AppBar(
          title: Align(
            alignment: Alignment(-0.2, 0.3),
            child: Text(
              cname,
            ),
          ),
        ),
        body: Center(
          child: FutureBuilder<Herbslist>(
            future: fetchPost(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return ListView.builder(
                  shrinkWrap: true,
                  itemCount: snapshot.data.query.pages.length,
                  itemBuilder: (BuildContext context, int index) {
                  //  var gcm = snapshot.data.herbslistContinue.gcmcontinue;
                    var img = snapshot.data.query.pages.values
                        .toList()[index]
                        .thumbnail
                        .source;
                    return Container(
                        child: Card(
                            child: GestureDetector(
                      onTap: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => Detailpage(
                                snapshot.data.query.pages.values
                                    .toList()[index]
                                    .title,
                              ),
                            ));
                      },
                      child: ListTile(
                        contentPadding: EdgeInsets.symmetric(
                            horizontal: 8.0, vertical: 8.0),
                        leading: Container(
                            padding: EdgeInsets.only(right: 10.0),
                            decoration: new BoxDecoration(
                              border: new Border(
                                  right: new BorderSide(
                                      width: 1.5, color: Colors.grey)),
                            ),
                            // ignore: unrelated_type_equality_checks
                            child: img == img.isEmpty
                                ? SizedBox(
                                    height: 50.0,
                                    width: 50.0,
                                    child: Image.asset('image.png'),
                                  )
                                : SizedBox(
                                    height: 50.0,
                                    width: 50.0,
                                    child: FadeInImage.assetNetwork(
                                      placeholder: 'image.png',
                                      image: img,
                                      fit: BoxFit.fill,
                                    ),
                                  )),
                        title: Text(snapshot.data.query.pages.values
                            .toList()[index]
                            .title),
                      ),
                    )));
                  },
                );
              } else {
                return Center(
                  child: CircularProgressIndicator(),
                );
              }
            },
          ),
        ));
  }
}


  [1]: https://app.quicktype.io/

标签: jsonflutter

解决方案


你可以做这样简单的事情,假设变量jsonMap是你上面显示的 json:

jsonMap['query']['pages'].values.toList()

编辑:编辑以更改为评论中建议的更好解决方案。

这是一个如何将其应用于代码的示例:

FutureBuilder<Herbslist>(
  future: fetchPost(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      List pages = snapshot.data['query']['pages'].values.toList();
      return ListView.builder(
        shrinkWrap: true,
        itemCount: pages.length,

确保更改其余代码以使用新pages变量。


推荐阅读