Swift:解析 Json 字符串并将信息填充到字典中 [英] Swift: Parsing Json string and populating information into a dictionary

查看:67
本文介绍了Swift:解析 Json 字符串并将信息填充到字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习 Swift 中的网络服务.我有这个 URL,显示最近的地震和其他有关它的信息.底部的代码是我到目前为止所拥有的,一旦我运行它,它就会从 URL 中 NSLogs JSON 格式的字符串.这是我从字符串中获得的 3 条记录.如何解析此 JSON 字符串并取出 ID、标题并将该信息填充到字典中?

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
    }

代码

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)")
            }

        }
    )

}

}

推荐答案

您可以使用类似于我在下面的内容提取那些id"和title"键值.在此例程结束时,您的所有数据都位于字典数组 newArrayofDicts 中.

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.

基本上,您只需使用 NSJSONSerialization.JSONObjectWithData 生成一个字典数组,然后跳入数组中的每个字典,并创建一个只有id"键值和title"的新字典" 密钥对.然后将这些字典中的每一个保存在某处.在下面的代码片段中,我将它们保存到 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.

这篇关于Swift:解析 Json 字符串并将信息填充到字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆