在Swift 3中解析JSON响应
我有一个API端点,它以以下格式返回JSON:在Swift 3中解析JSON响应,json,swift,http,Json,Swift,Http,我有一个API端点,它以以下格式返回JSON: [ { "id": "1", "name": "John" }, { "id": "2", "name": "Jane" }, { "id": "3", "name": "Nick" } ] 我试图在Swift 3中解析这一点,但我只能找到解析JSON格式的示例,如下所示: { "blogs": [ { "needspassword": true,
[
{
"id": "1",
"name": "John"
},
{
"id": "2",
"name": "Jane"
},
{
"id": "3",
"name": "Nick"
}
]
我试图在Swift 3中解析这一点,但我只能找到解析JSON格式的示例,如下所示:
{
"blogs": [
{
"needspassword": true,
"id": 73,
"url": "http://remote.bloxus.com/",
"name": "Bloxus test"
},
{
"needspassword": false,
"id": 74,
"url": "http://flickrtest1.userland.com/",
"name": "Manila Test"
}
],
"stat": "ok"
}
,它比我的有一个额外的等级
所以,我看到的示例只是解析他们的数据,比如jsonResponse[blogs],我不能这样做,因为我的格式不同
我如何解析我得到的格式,或者如何返回一个更容易解析的格式
任何建议,谢谢 我真的不知道swift,但是可能有ajax-json编码的等价物,服务器端json\u编码数组,客户端json\u解码响应
其想法是使用相同的格式化程序对数据进行编码和解码您只需执行以下操作:
let data = // Data received from WS
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [[String : String]]
//json is now an array from dictionary matching your model
}
catch {
//handle error
}
这将在放入网络调用时解析它
do {
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as! [[String : AnyObject]]
let firstPerson = json[0]
print(firstPerson)
let id = firstPerson["id"] as! String
print(id)
let name = firstPerson["name"] as! String
print(name)
} catch {
//handle error
}
此外,我倾向于反对向第三方库提供建议,但我认为SwiftyJSON是个例外。如果要尝试,请将以下内容添加到pod文件:
pod SwiftyJSON“3.0.0”
文件:
编辑-回答评论:
更换线:
if let id = firstPerson["id"] as? String {
print(id)
}
替换行,如果需要保留该值:
var thisId: String?
if let id = firstPerson["id"] as? String {
thisId = id
}
print(thisId ?? "")
我迟到了,但我想知道些什么。在这行中:让id=firstPerson[id]作为!一串如果firstPerson[id]值为零,是否会导致崩溃?是的,替换行将是我在编辑中添加的内容。永远不要回答特定语言的问题,以“我真的不知道”开头。把时间花在堆栈溢出上,检查适用于知识库的问题。