SWIFT 如何解析 JSON数组-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文
阿里云
为了无法计算的价值
打开APP
阿里云APP内打开

SWIFT 如何解析 JSON数组

[{"Date(time)":"2015-12-01","DayOfWeek(time)":"3","Time(time)":"11:38:23","Hour(time)":"11"},
 {"Date(time)":"2015-12-02","DayOfWeek(time)":"4","Time(time)":"11:38:23","Hour(time)":"11"},
 {"Date(time)":"2015-12-03","DayOfWeek(time)":"5","Time(time)":"12:38:23","Hour(time)":"12"},
 {"Date(time)":"2015-12-04","DayOfWeek(time)":"6","Time(time)":"11:38:23","Hour(time)":"11"},
 {"Date(time)":"2015-12-05","DayOfWeek(time)":"7","Time(time)":"11:38:23","Hour(time)":"11"}]

以上JSON数组如何解析?是json数组 ,单个的json已经回解析了,下面是解析单个json的方法
var json : AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil)!
 var name: AnyObject? = json[0].objectForKey("name")

展开
收起
杨冬芳 2016-07-06 16:12:35 2470 0
1 条回答
写回答
取消 提交回答
  • 杨冬芳
    IT从业

    json没有单个和json数组之分,只有json里是数组还是字典的分别,楼主给出的数据可见该json数据是由一个数组包裹着5个字典组成,解析方法如下:
    let resultArray = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as? Array
    resultArray则为包括着5个字典的数组。

    还有目前swift2 后 JSONObjectWithData操作需要try catch :
    写法1:
    var resultDict: NSArray?
    do {
    resultDict = try NSJSONSerialization.JSONObjectWithData(nonNilData, options: NSJSONReadingOptions.MutableContainers) as? NSArray
    } catch {
    debugPrint("JSONObjectWithDataError: (error)")
    }
    写法2:
    var resultDict = try? NSJSONSerialization.JSONObjectWithData(nonNilData, options: NSJSONReadingOptions.MutableContainers) as? NSArray

    建议json解析完后转换成json的真实类型,不要继续拿着anyObject来使用:
    例:如果json为字典 则: let MyDict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as? Dictionary

    可以用swiftjson这个第三方模块 封装很好
    http://www.cocoachina.com/ios/20140921/9703.html

    2019-07-17 19:52:15
    赞同 展开评论 打赏
问答排行榜
最热
最新
相关电子书
更多
OpenStack Swift 海量小文件优化之路
立即下载
OpenStack Swift 海量小文件性能优化之路
立即下载
From Java_Android to Swift iOS
立即下载