0

I'm currently learning about web services in Swift. I have this URL that shows recent earthquakes and other information regarding it. The code at the bottom is what I have so far, once I run it, it NSLogs a string in JSON format from the URL. Here are 3 records I have from the string. How do I parse this JSON string and take out the ID, title, and populate that information into a dictionary?

html = 
[
    {
        "response":1,
        "message":"OK",
        "count":50
    },
    {
        "id":133813,
        "title":"M 1.4 - 8km NE of Desert Hot Springs, California",
        "link":"http://earthquake.usgs.gov/earthquakes/eventpage/ci37312936",
        "source":"http://www.kuakes.com",
        "north":34.02,
        "west":116.443001,
        "lat":34.019501,
        "lng":-116.442497,
        "depth":1,
        "mag":1.4,
        "time":"2015-02-04 23:41:06 UTC",
        "timestamp":1423093266
    },
    {
        "id":133814,
        "title":"M 1.3 - 9km NE of Desert Hot Springs, California",
        "link":"http://earthquake.usgs.gov/earthquakes/eventpage/ci37312920",
        "source":"http://www.kuakes.com",
        "north":34.021,
        "west":116.441002,
        "lat":34.020832,
        "lng":-116.440666,
        "depth":1,
        "mag":1.3,
        "time":"2015-02-04 23:40:26 UTC",
        "timestamp":1423093226
    },
    {
        "id":133815,
        "title":"M 1.1 - 3km SW of Houston, Alaska",
        "link":"http://earthquake.usgs.gov/earthquakes/eventpage/ak11502658",
        "source":"http://www.kuakes.com",
        "north":61.604,
        "west":149.867004,
        "lat":61.6035,
        "lng":-149.866806,
        "depth":48,
        "mag":1.1,
        "time":"2015-02-04 23:38:42 UTC",
        "timestamp":1423093122
    }

The code

override func viewDidLoad() {
    super.viewDidLoad()

    let httpMethod = "GET"

    /* We have a 15-second timeout for our connection */
    let timeout = 15

    var urlAsString = "http://www.kuakes.com/json/"


    let url = NSURL(string: urlAsString)

    /* Set the timeout on our request here */
    let urlRequest = NSMutableURLRequest(URL: url,
        cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
        timeoutInterval: 15.0)

    urlRequest.HTTPMethod = httpMethod

    let queue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(urlRequest,
        queue: queue,
        completionHandler: {(response: NSURLResponse!,
            data: NSData!,
            error: NSError!) in

            if data.length > 0 && error == nil{
                let html = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("html = \(html)")
            } else if data.length == 0 && error == nil{
                println("Nothing was downloaded")
            } else if error != nil{
                println("Error happened = \(error)")
            }

        }
    )

}

}

1
  • 1
    Go to json.org and learn the JSON syntax. It only takes 5-10 minutes to learn. Commented Feb 5, 2015 at 2:42

1 Answer 1

3

You can pull those "id" and "title" key-values out using something similar to what I have below. At the end of this routine, all of your data sits in an array of dictionaries, newArrayofDicts.

Basically you just generate an array of dictionaries using NSJSONSerialization.JSONObjectWithData, and then hop into each dictionary in the array, and create a new dict with just the "id" key-value and "title" key-pair. Each of those dictionaries you then save somewhere. In the snippet below I save them to newArrayofDicts.

if data.length > 0 && error == nil{
    let html = NSString(data: data, encoding: NSUTF8StringEncoding)
    println("html = \(html)")

    var newArrayofDicts : NSMutableArray = NSMutableArray()
    var arrayOfDicts : NSMutableArray? = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error:nil) as? NSMutableArray
    if arrayOfDicts != nil {
        for item in arrayOfDicts! {
            if var dict  = item as? NSMutableDictionary{
                var newDict : NSMutableDictionary = NSMutableDictionary()
                if dict["title"] != nil && dict["id"] != nil{
                    newDict["title"] = dict["title"]
                    newDict["id"] = dict["id"]
                    newArrayofDicts.addObject(newDict)
                }
            }
        }
    }
}

There might be a snazzier way of going about this; but none comes to mind ;) It could also be made more succinct, but I feel it gets the idea across. Also, most of the objects created in the snippet above are mutable. That may not be necessary in your situation. You may want to adjust as needed. Hope that reasonably answered your question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.