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

穆理
2023-12-01

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

{

"total":2,

"status":"ok",

"data":[

{

"id":1,

"name":"周杰伦",

"head_image":null,

"tel":"1323232232",

"email":"zhoujielun@hotmail.com",

"birth_day":"1990-02-02",

"address":"中国香港"

},

{

"id":2,

"name":"庄心妍",

"head_image":null,

"tel":"1343432345",

"email":"zhuangxinyan@126.com",

"birth_day":"1986-05-22",

"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)

    }


 类似资料: