Swift 2将Json解析为可选数组

编程入门 行业动态 更新时间:2024-10-27 02:23:09
本文介绍了Swift 2将Json解析为可选数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在从Web服务获取国家/地区列表.收到它后,我使用以下代码对其进行处理:

I am getting list of countries from a web service. After receiving it I used this code to process it:

if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { // triggering callback function that should be processed in the call // doing logic } else { if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? AnyObject { completion(json) } else { let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding) print("Error could not parse JSON string: \(jsonStr)") } }

然后该列表看起来像这样(它在此部分NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? AnyObject中结束):

And after that list looks like this (it ends up in this part NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? AnyObject) :

Optional(( { "country_code" = AF; "dial_code" = 93; id = 1; name = Afghanistan; }, { "country_code" = DZ; "dial_code" = 213; id = 3; name = Algeria; }, { "country_code" = AD; "dial_code" = 376; id = 4; name = Andorra; } ))

我现在应该将此json对象转换为数组(或以某种方式转换为NSDictionary)并遍历它.有人可以建议吗?

I should now convert this json object to array (or NSDictionary somehow) and to loop through it. Can someone advice how?

推荐答案

当前,您无法遍历对象,因为该对象已被您的代码强制转换为AnyObject.使用当前代码,您正在投射as? NSDictionary或as? AnyObject的JSON数据.

Currently you can't loop through your object because it has been cast as AnyObject by your code. With your current code you're casting the JSON data either as? NSDictionary or as? AnyObject.

但是由于JSON总是以字典或数组开头,因此您应该这样做(保留示例):

But since JSON always start with a dictionary or an array, you should do this instead (keeping your example):

if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { // process "json" as a dictionary } else if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? NSArray { // process "json" as an array } else { let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding) print("Error could not parse JSON string: \(jsonStr)") }

理想情况下,您将使用Swift词典和数组而不是Foundation的NSDictionary和NSArray,但这取决于您.

And ideally you would use Swift dictionaries and arrays instead of Foundation's NSDictionary and NSArray, but that is up to you.

更多推荐

Swift 2将Json解析为可选数组

本文发布于:2023-11-26 22:44:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635507.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   数组   Swift   Json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!