我目前正在学习Swift中的Web服务。我有这个URL,显示最近的地震和有关它的其他信息。底部的代码是我到目前为止的代码,一旦我运行它,它就会从URL中以JSON格式NSLogs一个字符串。这是我从字符串中获得的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)")
}
}
)
}
}
答案 0 :(得分:3)
你可以拉那些" 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)
}
}
}
}
}
可能有一种更加流行的方式来解决这个问题;但是没有人想到;)它也可以更简洁,但我觉得它可以解决这个问题。此外,上面代码段中创建的大多数对象都是可变的。在您的情况下可能没有必要。您可能需要根据需要进行调整。希望合理地回答你的问题。