Prabhakar Patil
Prabhakar Patil

Reputation: 29

Setting the value in NSDictionary from JSON response

I have parsed the JSON data, now while setting the JSON to my NSDictionary there might be certain keys in the JSON that might not be present. I want to check if the key is present in the JSON parsed to me and if not, set blank field as value to the key in the `NSDictionary' object.

jsonData = ["id": ((json["idnumber"]) as? String!)!,
          "Name": ((json["name"]) as? String!)!,
   "Roll Number": ((json["rollnumber"]) as? String!)!,
         "Class": ((json["class"]) as? String!)!,
         "Marks": ((json["marks"]) as? String!)!,
        "Gender": ((json["gender"]) as? String!)!]

So in the above case, the marks field may or may not be present in the JSON. I want to check this and assign respective value to the corresponding key in jsonData.

I tried using "??", but it takes lot of compilation time.

Upvotes: 0

Views: 232

Answers (2)

Nirav D
Nirav D

Reputation: 72440

You can use if let or guard for conditional optional wrapping for that like this.

var jsonData = [String : String]
if let num = json["idnumber"]) as? String {
    jsonData["id"] = num
}
else {
    jsonData["id"] = num
}

and so on for others.

Edit: You can also try like this.

var id = name = rollNum = class = ""
if let num = json["idnumber"]) as? String {
    id = num
}
if let sname = json["name"]) as? String {
    name = sname
}
...

Then at last create Dictionary

var jsonData = ["id": id, "name": name, ...]

Upvotes: 0

pkc
pkc

Reputation: 8516

You can set the value if present otherwise blank string (""). This will prevent crash. Try below code:-

        let idValue = dictionary["idnumber"] as? String ?? ""
        let name = dictionary["name"] as? String ?? ""
        let rollNumber = dictionary["rollnumber"] as? String ?? ""
        let className = dictionary["class"] as? String ?? ""
        let marks = dictionary["marks"] as? String ?? ""
        let gender = dictionary["gender"] as? String ?? ""

        let jsonDic : NSMutableDictionary = NSMutableDictionary()
        jsonDic.setObject(idValue, forKey: "id")
        jsonDic.setObject(name, forKey: "name")
        jsonDic.setObject(className, forKey: "class")
        jsonDic.setObject(rollNumber, forKey: "rollNumber")
        jsonDic.setObject(marks, forKey: "marks")
        jsonDic.setObject(gender, forKey: "gender")

Upvotes: 0

Related Questions