Michael
Michael

Reputation: 123

swiftyJSON check if value is null

I have a json which is array of dictionary

response.text = [{
"id": "4635465675",
"name": "Arts",
"pluralName": "Arts",
"shortName": null
}]

json = JSON((response.text)?.data(using: .utf8)) How can i check is value for key "shortName" null or not, say for first dictionary in the array ? I tried to do like this

if json[0]["shortName"] is NSNull

But it's always true. How can i handle it?

Upvotes: 7

Views: 5542

Answers (3)

Anbu.Karthik
Anbu.Karthik

Reputation: 82759

you can directly check as the key of JSON.null

if json[0]["shortName"] == JSON.null {
// show the alert

}

if its your String

if json[0]["shortName"].string == nil {

Upvotes: 23

Michael
Michael

Reputation: 123

Ok, that's was easier than i was thinking

if json[0]["shortName"].string == nil {
//null
}else{
//not null
}

Upvotes: 0

Krunal
Krunal

Reputation: 79646

Execute following code and see

let jsonArray = [{ "id": "4635465675", "name": "Arts", "pluralName": "Arts", "shortName": null }] 

if let jsonObject = jsonArray[0] as? [String : Any] {

    if let id = jsonObject["id"] as? String {
       print("id - \(id)")
    } else {
       print("id does not exist or it is null/nil")
    }

    if let name = jsonObject["name"] as? String {
       print("name - \(name)")
    } else {
       print("name does not exist or it is null/nil")
    }

    if let pluralName = jsonObject["pluralName"] as? String {
       print("pluralName - \(pluralName)")
    } else {
       print("pluralName does not exist or it is null/nil")
    }

    if let shortName = jsonObject["shortName"] as? String {
       print("shortName - \(shortName)")
    } else {
       print("shortName does not exist or it is null/nil - \(jsonObject["shortName"])")
    }


}

Share here result of this code.

Upvotes: 0

Related Questions