json - Swift:解析 Json 字符串并将信息填充到字典中

标签 json swift nsstring nsdictionary

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

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 中。

基本上,您只需使用 NSJSONSerialization.JSONObjectWithData 生成字典数组,然后跳转到数组中的每个字典,并创建一个仅包含“id”键值和“title”的新字典" key 对。然后您将这些词典中的每一个保存在某个地方。在下面的代码片段中,我将它们保存到 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)
                }
            }
        }
    }
}

可能有更时髦的方法来解决这个问题;但没有想到 ;) 它也可以变得更简洁,但我觉得它传达了这个想法。此外,上面代码片段中创建的大多数对象都是可变的。在您的情况下,这可能没有必要。您可能需要根据需要进行调整。希望能合理回答您的问题。

关于json - Swift:解析 Json 字符串并将信息填充到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28335280/

相关文章:

objective-c - 如何在 NSCollectionView 中绘制 bezierPath?

ios - 基于重复子字符串或 2 个字符串之间的差异的 NSString 压缩

javascript - 使用 mySQL、Php 和 JS,我如何请求 dans 使用我数据库中的数据?

javascript - 谷歌地图 - 来自外部 json 的多个标记

javascript - 用对象中的对象构建Json(JS)

ios - Swift:根据唯一值合并数组中的 2 个或更多元素自定义对象

Python 请求 JSON

swift - 在 macOS 中访问打开文档的封闭文件夹的权限

ios - 删除 NSString 的最后一个字符,直到遇到分隔符

ios - 在 iOS 中通过蓝牙在两个设备之间传输 NSString