简体   繁体   English

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

[英]How do I get the value of a bool from a JSON in Swift3/Swift4?

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

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

I'm trying to get the value of "is_valid" from responseString dictionary.我正在尝试从responseString字典中获取"is_valid"的值。 However, I have no idea how.但是,我不知道如何。 Everything I've tried has failed.我尝试过的一切都失败了。

responseString looks like this when outputted via print() :当通过print()输出时responseString看起来像这样:

{
  "is_valid": true
}

You can use like this :你可以这样使用:

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

For completeness, a solution using Swift 4 new encoding/decoding framework ;)为完整起见,使用 Swift 4 新编码/解码框架的解决方案;)

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

Parse the JSON in the data with JSONSerialization :使用JSONSerialization解析data的 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 { ... }

This is another way you could find the Boolean value and keep it stored in a Struct这是您可以找到布尔值并将其存储在 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)
 }

}

Now let's say your loading from a JSON file within the app.现在假设您从应用程序中的 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)
    }
  } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM