ios - 如何在swift4中从json数组获取值

标签 ios json swift iphone

我无法将 json 值放入变量中。我正在打印值,但问题是我无法在没有数组的情况下获取 json 值

这是我的 json

{
"Categories": [
    "city",
    "delhi"
   ]
}

我想用数组对值进行分类,并用数组打印值

这是我的代码

do{
            let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]
            print(json as AnyObject)

            if let Categories = json["Categories"] {
                print(Categories)
            }

最佳答案

你需要

 do {

     let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:[String]]
      let arr1 = json["Categories"]!
      let str1 =  arr1.joined(separator: ":")
       print(str1)
     // or 
      let decoded = try JSONDecoder().decode(Root.self, from: data)
       let str =  decoded.categories.joined(separator: ":")
       print(str)

 } catch {
     print(error)
 }

或使用

struct Root: Codable {
    let categories: [String] 
    enum CodingKeys: String, CodingKey {
        case categories = "Categories"
    }
}

关于ios - 如何在swift4中从json数组获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55004044/

相关文章:

ios - becomeFirstResponder 后键盘隐藏

javascript - D3.js 使用外部数据强制布局图空白

ruby-on-rails - 传递与 id 不同的参数以返回 JSON 用户对象的正确 Rails 路由是什么?提供 Controller 方法

c# - 如何将参数传递给反序列化json的构造函数

swift - Swift 和 SpriteKit 如何将用户的分数转移到另一个场景?

ios - MKMapView 只调用一次 didSelect 回调

ios - 在表格 View 中显示数据

objective-c - UIScrollview 中的多个 Tableview

ios - 如何仅用一个 UIImageView 显示相册中的所有照片?

swift - 为什么不减少短路?