簡體   English   中英

如何快速獲取特定的 json 值

[英]how to get particular json value in swift

我想要 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.")
         }

請學會閱讀 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

您只需要從 newValue 中提取 size 。 嘗試這個

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.")
    }
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"])")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM