Swift ︰ 解析 Json 字符串和填充到字典的信息

发布时间: 2017/3/4 22:04:39
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我目前正在学习关于 web 服务在 Swift 。我有此 URL 显示最近发生的地震和其他资料。在底部的代码是什么吗到目前为止,一旦我运行它,它 NSLogs 在 JSON 字符串格式的 url。这里有 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)")
            }

        }
    )

}

}

解决方法 1:

你可以把这些"id"和"标题"键-值进行使用类似于下图。在结束这个例程时,您的所有数据坐在数组的词典, newArrayofDicts

基本上你只是生成的词典使用数组 NSJSONSerialization.JSONObjectWithData ,然后跳进在数组中,每个词典和创建新的字典只是"id"键-值和"标题"密钥对。每个词典然后保存在某个地方。在下面的代码段保存到 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)
                }
            }
        }
    }
}

有可能是一个时髦的方法不会感到这;但是没有一个人介意;)它还可更简洁,但我觉得它穿过了这个想法。此外,上述片段中创建的对象的大多数是可变的。那不可能需要在您的具体情况。你可能想要根据需要调整。合理地回答你的问题的希望。

赞助商