【问题标题】:how to get particular json value in swift如何快速获取特定的json值
【发布时间】:2019-03-08 11:15:51
【问题描述】:

我想要 json 对象中的大小值,但问题是我正在获取整个 json 数据,我只想打印大小值

这是我的 json

[{
   size = {
    height = 20
    width = 10
    },
    number = 100
}]

这是我的代码

     do{
            let Json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
            //print(Json as Any)

            guard let newValue = Json as? [[String: Any]] else {
                print("invalid format")
                return
            }
            print(newValue)

        }catch {
            print("Response Not Found.")
         }

【问题讨论】:

  • 您只需要获取尺寸键即可打印尺寸。如需参考,请点击此链接stackoverflow.com/questions/40736924/…
  • 你能帮我写个代码吗
  • 亲爱的,请先尝试,如果您有任何问题,请告诉我们....我们一定会帮助您....
  • 我正在获取整个 json 数据,我只想调整值的大小
  • 嘿@username000,你解析后得到的模型是数组。您需要先获取该数组的索引,然后再获取键值对。您的案例将是 newValue[]["Key"] 或试用,您可以执行 newValue.first["key"]

标签: json swift


【解决方案1】:

请学习阅读 JSON,很简单,只有两种集合类型:

  • [] 是数组,Swift [Any] 但在几乎所有情况下 [[String:Any]],通过索引订阅访问。
  • {} 是字典,Swift [String:Any],通过密钥订阅访问

永远不要在 Swift 中使用mutableContainers 选项,它根本没有任何作用。

if let json = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
    for item in json {
        if let size = item["size"] as? [String:Any] {
            print(size["height"], size["width"])
        }
    }
}

并且变量名应该以小写字母开头。

PS:你必须转换heightwidth的类型。输出——实际上是不是 JSON——是模棱两可的,你看不到值是String还是Int

【讨论】:

  • mutableContainers 选项应该做什么(是?)?
  • @Fehniix 这是一个与 Objective-C 相关的选项,用于将结果分配给 NSMutable… 对象,这在 Swift 中没有意义。如果将结果分配给let 常量,无论如何都是没有意义的。
【解决方案2】:

您只需要从 newValue 中提取大小。试试这个

do  {
        let Json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
        guard let newValue = Json as? [[String: Any]],
            let size = newValue[0]["size"] as? [String:Any] else {
                return
        }
        print(size)
    }
    catch {
        print("Response Not Found.")
    }

【讨论】:

    【解决方案3】:
    guard let newValue = Json as? [[String: Any]] else {
         print("invalid format")
         return
    }
    print(newValue["size"]) 
    

    或者如果你想要高度和宽度

    var sizeDict = newValue["size"] as! [String:Any]
    
    print("Width - \(sizeDict["width"])")
    print("Width - \(sizeDict["height"])")
    

    【讨论】:

    • 我收到错误无法使用“String”类型的索引为“[[String : Any]]”类型的值下标
    • 字典存在于数组中,newValue["size"] 会出错。你可以更正你的答案,陈述相同的内容。
    • var sizeDict = newValue[0]["size"]
    • foreach 语句
    • for dict in newValue { dict["size"] }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    相关资源
    最近更新 更多