Praveen Praveen - 20 days ago 8
JSON Question

Parsing embedded Json Dictionaries in Swift 3

The conversion to swift 3 has caused some errors in the code i use to parse Json. I have searched up others who had similar problems but none of them were instances were there were dictionaries within dictionaries and so forth. I understand the need to now cast the "any" portion when pulling information from dictionaries but I am not sure how to proceed with embedded ones. My code is below

func parseJson(_ JsonDict: NSDictionary)
{
var data = [newsarticle]()
var placeholder: NSDictionary
var names = JsonDict["result"]!["ReturnValue"]!!["tree"] as! [NSArray]
let childDict = names[0] as! NSDictionary
names = childDict["children"] as! NSArray
for element in names{
placeholder = element as! NSDictionary
data.append(newsarticle(name: placeholder["text"] as! String,desc: "https://www.oncoursesystems.com/school/webpage/\(placeholder["id"] as! NSNumber)/689493"))
}
addData(data)

}


The Json Dict I am parsing:

{
"type":"rpc",
"tid":2,
"action":"Websites",
"method":"school_webpage",
"result":{
"CurrentStatus":1,
"Description":"OK",
"ReturnValue":{
"splash":"",
"bgcolor":"#FFFFFF",
"tree":[
{
"text":"Staff Websites",
"expanded":true,
"children":[
{
"id":462793,
"text":"Ahrens, Linda",
"iconCls":"icn-add",
"leaf":true,
"type":"website",
"showAdd":false
},
{
"id":498858,
"text":"Altemose, David",
"iconCls":"icn-add",
"leaf":true,
"type":"website",
"showAdd":false
},
{
"id":11159347,
"text":"Alvin, Patrick",
"iconCls":"icn-add",
"leaf":true,
"type":"website",
"showAdd":false
},
{
"id":492376,
"text":"Anderson, Kelly",
"iconCls":"icn-add",
"leaf":true,
"type":"website",
"showAdd":false
},
{
"id":11247466,
"text":"Anderson, Michael",
"iconCls":"icn-add",
"leaf":true,
"type":"website",
"showAdd":false
}

]
}
]
}
}
}

Answer

The correctly modified version based off of Amit's code

func parseJson(_ JsonDict: AnyObject)
        {
            var data = [newsarticle]()
            let dict = JsonDict as? [String: AnyObject]
                if let dict2 = dict?["result"]?["ReturnValue"]{
                    if let dict3 = (dict2 as! [String: AnyObject])["tree"]  as? [AnyObject] {
                        for dict4  in dict3 {
                            if let dict5 = dict4["children"]  as? [AnyObject]{
                                for dict6 in dict5{
                                    let datum = dict6 as? [String: AnyObject]
                                    data.append(newsarticle(name: (datum?["text"])! as! String,desc: "https://www.oncoursesystems.com/school/webpage/\(datum?["id"] as! NSNumber)/689493"))
                                }

                            }
                        }
                        addData(data)
                    }
                }
        }
Comments