快速从服务器响应中获取价值
Posted
技术标签:
【中文标题】快速从服务器响应中获取价值【英文标题】:Get value from server reponse swift 【发布时间】:2017-08-09 07:34:52 【问题描述】:我是 Swift 新手, 我想从服务器响应中获取纬度和经度的值。
我如何获得价值?
这是我的代码:
WebServiceHelper.sharedInstance.makeWebServiceCall(urlAddress: "http://jsonplaceholder.typicode.com/users/1", requestMethod: "GET", params: ["Key" : "value"], Success: (JSON:Any) in
print("Success Received data is: \(JSON)")
, Error: (JSON:Any) in
print("Error Received data is: \(JSON)")
) (JSON:Any) in
print("Header Received data is: \(JSON)")
我可以得到服务器响应这里是:
Success Received data is:
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address":
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo":
"latitude": "-37.3159",
"longitude": "81.1496"
,
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company":
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
我如何获得?
【问题讨论】:
JSONSerialization,然后转换成你的模型 检查这个问题***.com/questions/45019869/… 你能帮我搞定语法吗? 【参考方案1】:你可以试试这样来拉长:
if let result = JSON as? [String:AnyObject]
let address = result?["address"] as? [String:AnyObject]
let geo = address?["geo"] as? [String:AnyObject]
print(geo?["lng"])
print(geo?["lat"])
【讨论】:
我尝试了这段代码,但如果JSON
的条件值存在,则控件不会进入内部
好的!然后你可以在没有“ if ”条件的情况下使用它。
当我写这个let address = JSON["address"] as? [String:AnyObject]
时它给出了错误@
你必须这样写:let result = JSON as? [String:AnyObject] 让地址 = 结果?[“地址”] 为? [String:AnyObject] 让 geo = 地址?["geo"] as? [String:AnyObject] print(geo?["lng"]) print(geo?["lat"])
同样的问题 result
返回 nil以上是关于快速从服务器响应中获取价值的主要内容,如果未能解决你的问题,请参考以下文章