Tolgay Toklar Tolgay Toklar - 3 years ago 212
JSON Question

Json inside json with swift

I have to read following json:

lg = 1;
"ribbon_count" = {
"t_r1" = 10;
"t_r2" = 151;
"t_r3" = 0;
"t_r4" = 1;

I am reading
property with following lines:

let jsonResult: NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
let status=jsonResult["lg"] as! Int

But I don't know how to read
property. How can I read the

Answer Source

First of all use Swift collection types, they provide type information.
Second of all you probably don't need mutable containers.

let jsonResult = try! NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject]
let status = jsonResult["lg"] as! Int

The value of ribbon_count is a dictionary with String keys and Int values

let ribbonCount = jsonResult["ribbon_count"] as! [String:Int]
let tR1 = ribbonCount["t_r1"]!
let tR2 = ribbonCount["t_r2"]!
let tR3 = ribbonCount["t_r3"]!
let tR4 = ribbonCount["t_r4"]!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download