swift3读取本地json数据 --JSONSerialization.jsonObject()

前端之家收集整理的这篇文章主要介绍了swift3读取本地json数据 --JSONSerialization.jsonObject()前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、本地json数据如下:data.json

{

"total":2,

"status":"ok",19)"> "data":[

{

"id":1,19)"> "name":"周杰伦",19)"> "head_image":null,19)"> "tel":"1323232232",19)"> "email":"zhoujielun@hotmail.com",19)"> "birth_day":"1990-02-02",19)"> "address":"中国香港"

},

{

"id":2,19)"> "name":"庄心妍",19)"> "tel":"1343432345",19)"> "email":"zhuangxinyan@126.com",19)"> "birth_day":"1986-05-22",19)"> "address":"中国河南省"

}

}

2、模型数据UserData 如下:

class UserData: NSObject,NSCoding {


var name:String?

var tel:String?

var headImgUrlStr:String?

var email:String?

var address:String?

}


3、读取本地数据代码如下:

var userList:NSMutableArray?

let path =Bundle.main.path(forResource:"data",ofType: "json")

let url =URL(fileURLWithPath: path!)

do{

let data =tryData(contentsOf: url)

let json:Any =tryJSONSerialization.jsonObject(with: data,options:JSONSerialization.ReadingOptions.mutableContainers)

let jsonDic = jsonas!Dictionary<String,Any>

let datalist = jsonDic["data"]as!NSArray

userList = UserData.mj_objectArray(withKeyValuesArray: datalist)//该方法在第三个JSON解析库MJExtension中。你可以忽略本行代码

print(datalist)//输出数据

}catchlet erroasError!{

print("读取本地数据出现错误",erro)

}

原文链接:https://www.f2er.com/swift/322885.html

猜你在找的Swift相关文章