7

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?

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
Michael
  • 123
  • 2
  • 9

3 Answers3

23

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 {
melbic
  • 11,988
  • 5
  • 33
  • 37
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
  • YES, that's was exactly what i needed. THANKS – Michael Mar 05 '18 at 11:15
  • shouldn't `if json[0]["shortName"].stringValue == nil{` change to `if json[0]["shortName"].stringValue == ""{` as stringValue always returns String not String? – Wimukthi Rajapaksha Apr 06 '20 at 18:55
  • @WimukthiRajapaksha- thanks for your comment , we can also use like `if let getShortName = json[0]["shortName"].string,!getShortName.isEmpty { print(getShortName) }` – Anbu.Karthik Apr 07 '20 at 04:32
0

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.

Krunal
  • 77,632
  • 48
  • 245
  • 261
0

Ok, that's was easier than i was thinking

if json[0]["shortName"].string == nil {
//null
}else{
//not null
}
Michael
  • 123
  • 2
  • 9