AlexanderHart AlexanderHart - 5 months ago 14
JSON Question

Storing JSON Dictionary Values into Variables

Using a PHP file, I echoed data from a MySQL database in the following format:

[{"longitude":"-122.031","latitude":"37.3323”}]


In my Swift file, I use
NSJSONSerialization.JSONObjectWithData()
to create a JSON dictionary that looks like the following

(

{

latitude = "37.3323";

longitude = "-122.031";

}

)


If I wanted to store the individual dictionary values inside variables, I believe the following snippet of Swift code would work

class Location: NSObject {
var latitude: String?
var longitude: String?
}

var locations = [Location]()

if let locationDictionary = jsonDictionary["coordinates"] as? [String: AnyObject] {
let location = Location()

location.setValuesForKeysWithDictionary(locationDictionary)

print(location.latitude, location.longitude)
}


The only problem I’m having is that I need my JSON dictionary to look like

(

coordinates = {

latitude = "37.3323";

longitude = "-122.031";

}

)


but I don’t know what steps to take to achieve this.

Answer

You would have to make your JSON like this:

[{"coordinates":{"longitude":"-122.031","latitude":"37.3323"}}]

which is an array of dictionaries, where each dictionary contains another one.

And here is your code adapted for the new format:

if let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []), // your source may differ, I'm just using this line for my example
    content = json as? [[String:AnyObject]] { // the array of dictionaries
    for item in content {
        if let locationDictionary = item["coordinates"] as? [String: AnyObject] { // the dictionary inside the dictionary
            let location = Location()
            location.setValuesForKeysWithDictionary(locationDictionary)
            print(location.latitude, location.longitude)
        }
    }
}