如何从Swift3 / Swift4中的JSON获取bool的值?

时间:2017-10-07 22:02:01

标签: ios json swift swift4

let responseString = String(data: data, encoding: .utf8)

if responseString["is_valid"] == true {
    print("Login Successful")
} else {
    print("Login attempt failed")
}

我试图从"is_valid"字典中获取responseString的值。但是,我不知道怎么做。我尝试的一切都失败了。

通过responseString

输出时,

print()看起来像这样

{
  "is_valid": true
}

4 个答案:

答案 0 :(得分:2)

您可以这样使用:

if let responseString = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Bool] {
    if responseString!["is_valid"] == true {
        print("Login Successful")
    } else {
        print("Login attempt failed")
    }
}

答案 1 :(得分:1)

为了完整性,使用Swift 4新编码/解码框架的解决方案;)

let response = try? JSONDecoder().decode([String: Bool].self, from: data)
if response?["is_value"] {
    print("Login Successful")
} else {
    print("Login attempt failed")
}

答案 2 :(得分:0)

使用data

解析JSONSerialization中的JSON
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
    let isValue = json?["is_value"] as? Bool else { 
        // handle the failure to find `is_value` however you'd like here
        return 
}

if isValue { ... }

答案 3 :(得分:0)

这是找到布尔值并将其保存在Struct中的另一种方法

{
"is_valid" = true
}

struct Session: Codable {
var isValid: Bool

 //Create a coding key so you can match the struct variable name to JSON data key
 private enum CodingKeys: String, CodingKey {
   case isValid = "is_valid"
 }

 //Initialises and decodes the JSON data to fill your struct
 init(from decoder: Decoder) throws {
   let container = try decoder.container(keyedBy: CodingKeys.self)
   self.isValid = try container.decode(Bool.self, forKey: .isValid)
 }

}

现在,假设您是从应用程序中的JSON文件加载的。

func loadJSONData(){
  guard let url = Bundle.main.url(forResource: "myJSONFile", withExtension: "json") else { return }
 do {
      let data = try Data(contentsOf: url, options: .mappedIfSafe)
      let decoder = JSONDecoder()

      //decode data and populate Session struct
      guard let jsonData = try? decoder.decode(Session.self, from: data) else {return}

      if jsonData.isValid {
          print("DO SOMETHING HERE)
    }
  } 
}