Marin
Marin

Reputation: 12920

Swift Parsing JSON

I'm able to get JSON data because I can see it being printed out using println. I can also print some individual keys. However I'm having a hard time converting it to string.

var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:     NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
    println(jsonResult.count) // works
    numberOfStations.text = String(jsonResult.count)
    //latitude.text = jsonResult["latitude"] as String
    //var result: String = jsonResult["latitude"] as String
    let latitudeData : AnyObject? = jsonResult["latitude"]
    let longitudeData: AnyObject? = jsonResult["longitude"]

latitude.text = latitudeData as NSString!   // Doesn't work
longitude.text = longitudeData as NSString! // Doesn't work
println("latitude --> \(latitudeData)")    // Works  prints it ok latitude ---> 40.30303
println("longitude --> \(longitudeData)")  //Works   prints it ok longitude ---> 37.20202

JSON similar to this

{
latitude: 34.0522342,
longitude: -118.2436849,
station_counts: {
 total: 247,
 fuels: {
     E85: {
       total: 0
   },
   ELEC: {
     total: 225,
     stations: {
       total: 55
     }
   },
 }
}

Upvotes: 2

Views: 1090

Answers (3)

Pascal
Pascal

Reputation: 16941

You may want to take a look at SwiftyJSON, an open source library on GitHub that makes JSON processing in Swift real nice.

Upvotes: 1

Austen Chongpison
Austen Chongpison

Reputation: 3974

I would not recommend depending on description() to parse json. This is how I'm parsing json in Swift (beta 4)

            //parse Episode Name
            if let jsonAsDict = responseObject as? Dictionary<String, AnyObject>
            {
                if let array: AnyObject = jsonAsDict["episodes"]
                {
                    for item: AnyObject in array as [AnyObject]
                    {
                        //put episode name into array
                        self.episodeNames.append(item["name"] as String)
                    }
                }
            }

The json has this format:

            episodes: [
                {
                    name: "Episode Name 1"
                },
                {
                    name: "Episode Name2"
                }
            ]

self.episodeNames is declared as 'var episodeNames: [String]' in this example

Upvotes: 1

Kaelin Colclasure
Kaelin Colclasure

Reputation: 3975

Your code is attempting to convert the values by simply casting them to strings. You instead need to use a method that returns a string representation of the value. For example:

latitude.text = latitudeData!.description

Upvotes: 1

Related Questions