我正在尝试在我的 swift 代码中访问 JSON 数据,但无法使其正确返回。这是我的 JSON 代码:
[
{
"id": "1",
"isImage": "0",
"name": "test name",
"post": "test post",
"time": "10:27",
"ip": "192.168.1.1",
"city ": "Columbus",
"latlong": "39.896418,-82.9751105",
"clientID": "clientID",
"popularity": "300"
},
{
"id": "2",
"isImage": "0",
"name": "test name two",
"post": "test post two",
"time": "13:37",
"ip": "192.168.1.1",
"city ": "Columbus",
"latlong": "39.896418,-82.9751105",
"clientID": "clientID",
"popularity": "69"
}
]
我只是想知道如何通过键 json[0].['id']
访问数据还是?
我目前正在使用这个 json.swift module并尝试使用访问数据
func jsonHandle(data: NSString) {
var parsedJSON = JSON(data)
var id = parsedJSON[0].["id"]
NSLog("\(id)")
}
但它什么也没返回。有什么想法吗?
最佳答案
您可以调用 JSON(string:...)
再现并消除 [0]
和 ["id"]< 之间的句点
:
func jsonHandle(data: NSString) {
let parsedJSON = JSON(string: data)
var id = parsedJSON[0]["id"]
NSLog("\(id)")
}
或者,如果您有 NSData
,您可以使用 JSON(data: ...)
再现:
func jsonHandle(data: NSData) {
let parsedJSON = JSON(data: data)
let id = parsedJSON[0]["id"]
NSLog("\(id)")
}
或者,如果您想使用 native NSJSONSerialization
,而不是第三方库,您可以:
func jsonHandle(data: NSData) {
var error: NSError?
let parsedJSON = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as NSArray
let id = parsedJSON[0]["id"]
NSLog("\(id)")
}
就我个人而言,我倾向于标准 NSJSONSerialization
方法,因为它是一种经过验证的真实方法,但这是你的决定。
关于json - 快速访问 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27116256/