I’m not entirely sure what you mean by “nested json” but I suspect that you’re asking how to parse a dictionary within a dictionary. If so, here’s an example.
Let’s start with JSON data like this:
7b0a2020 22616464 72657373 22203a20
7b0a2020 2020227a 6970436f 64652220
3a202239 35303134 222c0a20 20202022
73747265 65744164 64726573 7322203a
20223120 496e6669 6e697465 204c6f6f
70222c0a 20202020 22636f75 6e747279
22203a20 22555341 220a2020 7d2c0a20
20226e61 6d652220 3a202241 70706c65
20496e63 2e220a7d
As text this looks like this:
{
"address" : {
"zipCode" : "95014",
"streetAddress" : "1 Infinite Loop",
"country" : "USA"
},
"name" : "Apple Inc."
}
You parse out the name and country like this:
do {
let rootUntyped = try NSJSONSerialization.JSONObjectWithData(data, options: [])
guard let rootDict = rootUntyped as? NSDictionary else {
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadCorruptFileError, userInfo: nil)
}
guard let name = rootDict["name"] as? String else {
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadCorruptFileError, userInfo: nil)
}
guard let address = rootDict["address"] as? NSDictionary else {
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadCorruptFileError, userInfo: nil)
}
guard let country = address["country"] as? String else {
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadCorruptFileError, userInfo: nil)
}
NSLog("name: %@", name)
NSLog("country: %@", country)
} catch let error as NSError {
NSLog("%@", error)
}
When run this prints:
2015-11-13 12:00:06.438 JSONTest[33964:2590782] name: Apple Inc.
2015-11-13 12:00:06.438 JSONTest[33964:2590782] country: USA
Now, this is a lot of code and there are better ways to do this (parsing JSON is like the “Hello World!” of Swift, that is, it’s a common place to start learning the details of the language) but the above works and represents a direct translation of how you might do it in Objective-C.
Share and Enjoy
—
Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"