【问题标题】:swift 3 parse json array as key valueswift 3 将 json 数组解析为键值
【发布时间】:2016-11-27 09:07:07
【问题描述】:

我有一个 json,我将其解析为字典。现在 most 只是一个键值对,例如“title”:{“this is the title”}。困扰我的一件事是一个键值对,它有一个值数组。

"hashTags":[{"name":"pizza"},{"name":"salami"},{"name":"diet"}]

我不想使用 SwiftyJSON,因为这是我唯一无法解决的部分。我需要的是将此值转换为一个数组,我可以对其进行迭代。我有一些方法,但它们失败了,因为它们添加了新行或停止显示 äöü 符号。

提前谢谢你!

【问题讨论】:

    标签: ios arrays json parsing swift3


    【解决方案1】:
    • hashTags 是带有 String 键和值的字典数组,将其转换为 [[String:String]]
    • 使用 for 循环遍历数组并打印键 name 的所有值

      if let hashTags = json["hashTags"] as? [[String:String]] {
         for tag in hashTags {
             print(tag["name"])
         }
      }
      

    假定json 是包含键hashTags 的父对象。

    【讨论】:

      【解决方案2】:

      您只需要使用可编码。

      您可以使用 Codable 轻松地将 Json 解析为您想要的模型。您可以查看以下文档以获取更多详细信息:

      https://developer.apple.com/documentation/foundation/archives_and_serialization/using_json_with_custom_types

      https://developer.apple.com/documentation/swift/codable

      【讨论】:

        猜你喜欢
        • 2017-02-07
        • 1970-01-01
        • 2018-03-19
        • 1970-01-01
        • 1970-01-01
        • 2019-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多