解析JSON响应3

解析JSON响应3

问题描述:

我已经得到了下面的格式返回JSON的API端点:解析JSON响应3

[ 
    { 
    "id": "1", 
    "name": "John" 
    }, 
    { 
    "id": "2", 
    "name": "Jane" 
    }, 
    { 
    "id": "3", 
    "name": "Nick" 
    } 
] 

我想在斯威夫特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"],我不能这样做,因为我的格式不同。

我该如何解析我得到的格式,或者如何返回更容易解析的格式?

任何建议表示感谢,谢谢!

放置在网络呼叫时,这将会对其进行解析。

 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文件:

荚SwiftyJSON”, '3.0.0'

文档:https://github.com/SwiftyJSON/SwiftyJSON

编辑 - 接听评论:

更换line:

if let id = firstPerson["id"] as? String { 
    print(id) 
} 

替换行(如果您需要保留该值):

var thisId: String? 
if let id = firstPerson["id"] as? String { 
    thisId = id 
} 
print(thisId ?? "") 
+0

嗯,我迟到了,但我想知道的东西。在这一行中:'let id = firstPerson [“id”] as! String'。如果'firstPerson [“id”]'值为零,是不是会导致崩溃? – Rikh

+0

是的,我将在编辑中添加替换行 – Sethmr

我真的不知道流畅但有可能是AJAX JSON编码(服务器端,您json_encode阵列,并且客户端你json_decode响应)

的想法是具有相同的格式编码的等价和解码数据

+1

永远不要回答一个语言特定的问题开始您的答案 “我真的不知道_____”。花你的时间堆栈溢出检查适用于你的知识库的问题。 – Sethmr

您只需做到以下几点:

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 
    }