【问题标题】:How to get all Json Body's Children, Flutter如何获得所有 Json Body 的孩子,Flutter
【发布时间】:2020-10-15 22:34:27
【问题描述】:

请问,如果我的 json 身体有多个这样的孩子。

 { "head": {    "title": "Podcasts",
    "status": "200"}, "body": [
 { "element" : "outline", 
"text" : "Music", 
"children": [
 { "element" : "outline", 
"type" : "link", 
"text" : "Schlager", 
"URL" : "http://opml.radiotime.com/Browse.ashx?id=c100000594&filter=p:topic", 
"guide_id" : "c100000594" },
 { "element" : "outline", 
"type" : "link", 
"text" : "Rádios da Metropolitana FM", 
"URL" : "http://opml.radiotime.com/Browse.ashx?id=c100002153&filter=p:topic", 
"guide_id" : "c100002153" },
 { "element" : "outline", 
"type" : "link", 
"text" : "Hits Popular", 
"URL" : "http://opml.radiotime.com/Browse.ashx?id=c100000599&filter=p:topic", 
"guide_id" : "c100000599" },
 { "element" : "outline", 
"type" : "link", 
"text" : "Top 40 & Pop Music", 
"URL" : "http://opml.radiotime.com/Browse.ashx?id=c57943&filter=p:topic", 
"guide_id" : "c57943" },
] },
 { "element" : "outline", 
"text" : "Talk", 
"children": [
 { "element" : "outline", 
"type" : "link", 
"text" : "International Public Radio", 
"URL" : "http://opml.radiotime.com/Browse.ashx?id=c100001487&filter=p:topic", 
"guide_id" : "c100001487" },
 { "element" : "outline", 
"type" : "link", 
"text" : "History Podcasts", 
"URL" : "http://opml.radiotime.com/Browse.ashx?id=c100000897&filter=p:topic", 
"guide_id" : "c100000897" },
 { "element" : "outline", 
] }
] }

我的代码只能得到第一个孩子。

List<Prodcasts> parseProdcasts(String responseBody) {
  var parsed = jsonDecode(responseBody)['body'][0]['children'] as List;
  return parsed.map<Prodcasts>((json) => Prodcasts.fromJson(json)).toList();
}

因为我输入了['body'][0]['children'],如果我想获得第二个孩子,我必须输入['body'][1]['children']

好的,但是如果我想得到所有的孩子怎么办? 提前致谢

【问题讨论】:

    标签: json flutter dart decode


    【解决方案1】:

    要获得孩子,您需要地图功能。

    jsonDecode(responseBody)['body'].map((item)=> item['children']).toList().expand((x) => x).toList()
    

    【讨论】:

    • 非常感谢您的帮助。我收到此错误异常:类型'(动态)=>字符串'不是'f'类型'(动态)=> Iterable'的子类型我想从所有孩子那里获取文本值; =>text = json['text'];
    • json.map((child)=> child['text']).toList() 将为您提供 children 中的文本列表
    • 非常感谢您抽出宝贵的时间,但正如我所说,我在使用 map func 后收到了一条错误消息,请您在opml.radiotime.com/Browse.ashx?render=json&c=podcast 使用 json 尝试您的功能,如果是的话工作请粘贴你的代码,看看我的代码和你的代码有什么不同,并知道我犯的错误。再次感谢
    猜你喜欢
    • 2019-10-14
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多