如何在Swift 3中使用循环打印JSON值?

编程入门 行业动态 更新时间:2024-10-26 14:35:35
本文介绍了如何在Swift 3中使用循环打印JSON值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我得到了这个JSON:

{ cover = { id = 1; }; description = "Test" place = { id = 11; location = { city = Wheatley; }; name = "Wheatley Provincial Park"; }; }, { cover = { id = 2; }; description = "Cool" place = { id = 22; location = { city = Wheatley; }; name = "Wheatley Provincial Park"; }; }

这是我的代码:

if let fbData = result as? [String : Any] { print(fbData) for events in fbData { print (events["name"] as! String) //this displays an error //Type (Key: String, value: Any) has subscript members }

}

但是我不知道如何遍历它们

我已经尝试过这些解决方案,但是它们从未起作用:

在Swift 3中进行JSON解析

在Swift 3中正确解析JSON

使用Swift 3解析JSON

解决方案

if let array = result as? [String : AnyObject]{ if let fbData = array["data"] as? [[String : AnyObject]] { print(fbData) for event in fbData { print (event["name"] as! String) } } }

  • result是Any类型
  • 将其发布到字典中-[String : AnyObject]
  • 提取data并转换为字典数组-[[String : AnyObject]].
  • I got this JSON:

    { cover = { id = 1; }; description = "Test" place = { id = 11; location = { city = Wheatley; }; name = "Wheatley Provincial Park"; }; }, { cover = { id = 2; }; description = "Cool" place = { id = 22; location = { city = Wheatley; }; name = "Wheatley Provincial Park"; }; }

    This is my code:

    if let fbData = result as? [String : Any] { print(fbData) for events in fbData { print (events["name"] as! String) //this displays an error //Type (Key: String, value: Any) has subscript members }

    }

    But I don't know how to loop through them

    I already tried these solutions but they never worked:

    JSON Parsing in Swift 3

    Correctly Parsing JSON in Swift 3

    Parsing JSON using Swift 3

    解决方案

    if let array = result as? [String : AnyObject]{ if let fbData = array["data"] as? [[String : AnyObject]] { print(fbData) for event in fbData { print (event["name"] as! String) } } }

  • result is of Any type
  • Cast it into Dictionary - [String : AnyObject]
  • Extract data and cast to Array of Dictionaries - [[String : AnyObject]].
  • 更多推荐

    如何在Swift 3中使用循环打印JSON值?

    本文发布于:2023-11-26 21:56:44,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1635353.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:如何在   Swift   JSON

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!