在 SWIFT 中将 JSON 解析为字典对象

Posted

技术标签:

【中文标题】在 SWIFT 中将 JSON 解析为字典对象【英文标题】:Parse JSON into dictionary object in SWIFT 【发布时间】:2015-04-10 22:31:04 【问题描述】:

我之前发布过这个问题 Swift: Parsing Json string and populating information into a dictionary

但我现在有一个稍微不同的问题。所以我再次发布这个修改后的问题。我是一名新开发人员,正在努力学习 SWIFT。

我在我的swift程序中调用web服务http://www.kuakes.com/json/如下

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

        

得到如下结果

["response":1,"message":"OK","count":50,"id":145608,"title":"M 0.9 爆炸 - 莫顿东 19 公里, 华盛顿","链接":"http://earthquake.usgs.gov/earthquakes/eventpage/uw60985917","来源":"http://www.kuakes.com","north":46.536999,"west" :122.021004,"lat":46.536499,"lng":-122.021164,"depth":0,"mag":0.9,"time":"2015-04-10 21:26:07 UTC","timestamp":1428701167,"id":145609,"title":"M 2.3 - 锚点西 27 公里, 阿拉斯加","链接":"http://earthquake.usgs.gov/earthquakes/eventpage/ak11550832","来源":"http://www.kuakes.com","north":59.820999,"west" :152.307999,"lat":59.820702,"lng":-152.308197,"depth":59,"mag":2.3,"time":"2015-04-10 20:30:09 UTC","timestamp":1428697809,"id":145610,"title":"M 2.2 - Red Bluff 23 公里 ENE, 加利福尼亚","链接":"http://earthquake.usgs.gov/earthquakes/eventpage/nc72429666","来源":"http://www.kuakes.com","north":40.293999,"west" :122.000999,"lat":40.294167,"lng":-122.001335,"depth":10,"mag":2.2,"time":"2015-04-10 20:19:01 UTC","timestamp":1428697141,"id":145611,"title":"M 2.8 - 多拉多以北 54 公里,波多黎各 Rico","link":"http://earthquake.usgs.gov/earthquakes/eventpage/pr15100004","source":"http://www.kuakes.com","north":18.951,"west" :66.219002,"lat":18.951401,"lng":-66.219101,"depth":28,"mag":2.8,"time":"2015-04-10 20:05:46 UTC","时间戳":1428696346,

我想将上面的 json 结果解析成一个字典对象,例如键是 id,值是对应字符串的其余部分。所以字典对象的第一个条目如下:

id = 145609"

title:"M 2.3 - 27km W of Anchor Point, 阿拉斯加","链接":"http://earthquake.usgs.gov/earthquakes/eventpage/ak11550832","来源":"http://www.kuakes.com","north":59.820999,"west" :152.307999,"lat":59.820702,"lng":-152.308197,"depth":59,"mag":2.3,"time":"2015-04-10 20:30:09 UTC","时间戳":1428697809

字典中的第二个条目会这样

id = 145609

"title":"M 2.2 - 23km ENE of Red Bluff, 加利福尼亚","链接":"http://earthquake.usgs.gov/earthquakes/eventpage/nc72429666","来源":"http://www.kuakes.com","north":40.293999,"west" :122.000999,"lat":40.294167,"lng":-122.001335,"depth":10,"mag":2.2,"time":"2015-04-10 20:19:01 UTC","timestamp":1428697141

等等等等……

我现在只想在单个字典对象中解析和填充键/值对。

【问题讨论】:

您不能拥有一个包含多个名为 id 的键的字典。键是唯一的。您是否想要一个字典数组,而您所称的第一个和第二个条目将是数组的第一个和第二个元素? 首先,您所拥有的是一个阵列。它包含一堆 JSON 对象(字典),其中第一个提供响应状态和计数,其余的似乎包含有关单个事件的信息。如果您想按照您的描述重新组织数据,只需编写代码即可。 【参考方案1】:

我建议你使用SwiftyJSON 之类的东西。

然后创建一个这样的类来存储东西:

class Entry 
    var title, link, source, north, west, lat, lng, dept, mag, time, timestamp

【讨论】:

以上是关于在 SWIFT 中将 JSON 解析为字典对象的主要内容,如果未能解决你的问题,请参考以下文章

在 Swift 中将字典转换为 JSON

在 Swift 中将字典转换为 JSON

在 Swift 3 中将 JSON 字符串转换为字典

解析 JSON 字典 Swift5

如何在ios中将字典的双引号数组解析为json?

如何在Swift中将键值对分解为JSON字符串?