Swift: 解析 Json 字符串并将信息填充到字典中
Swift: Parsing Json string and populating information into a dictionary
我目前正在 Swift 学习网络服务。我有这个 URL 显示最近的地震和其他相关信息。底部的代码是我目前所拥有的,一旦我 运行 它,它就会 NSLogs 来自 URL 的 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" 键值和 [=21] 的新字典=] 密钥对。然后您将这些词典中的每一个保存在某个地方。在下面的代码片段中,我将它们保存到 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)
}
}
}
}
}
可能有更时髦的方法来解决这个问题;但是我想到了 none ;) 它也可以做得更简洁,但我觉得它传达了这个想法。此外,上面代码片段中创建的大多数对象都是可变的。在您的情况下,这可能没有必要。您可能需要根据需要进行调整。希望能合理回答你的问题。
我目前正在 Swift 学习网络服务。我有这个 URL 显示最近的地震和其他相关信息。底部的代码是我目前所拥有的,一旦我 运行 它,它就会 NSLogs 来自 URL 的 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" 键值和 [=21] 的新字典=] 密钥对。然后您将这些词典中的每一个保存在某个地方。在下面的代码片段中,我将它们保存到 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)
}
}
}
}
}
可能有更时髦的方法来解决这个问题;但是我想到了 none ;) 它也可以做得更简洁,但我觉得它传达了这个想法。此外,上面代码片段中创建的大多数对象都是可变的。在您的情况下,这可能没有必要。您可能需要根据需要进行调整。希望能合理回答你的问题。