简体   繁体   中英

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. However, I have no idea how. Everything I've tried has failed.

responseString looks like this when outputted via print() :

{
  "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 ;)

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 :

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

{
"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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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