swfit json解析与闭包回调

2018-01-25  本文已影响0人  xiaoke123456

1.只包含一个模型类的字典解析

func JsonNormalModel() -> () {

  let jsonDic = ["userName":"beer", "age":"100","userEmail":"yaozuopan@icloud.com"] as [String : Any]

  let jsonData = try! JSONSerialization.data(withJSONObject: jsonDic, options: .prettyPrinted)

  let decode = JSONDecoder()

 if let user = try? decode.decode(Usre.self, from: jsonData){  print(user.userEmail)}

}

2.模型数组的字典解析

func JsonArrModel(complition:@escaping (_ list:[Usre])->()) -> () { 

 let mainDic = ["name":"软件部","id":"888","member":[["userName":"beer0", "age":"101","userEmail":"yaozuopan4@icloud.com"],["userName":"beer1", "age":"103","userEmail":"yaozuopan3@icloud.com"]]] as [String : Any]

let mainData = try! JSONSerialization.data(withJSONObject: mainDic, options: .prettyPrinted)

let decode1 = JSONDecoder()

if let group = try? decode1.decode(Department.self, from: mainData)

 {            var arrayM = [Usre]()

                for (indexs,item) in group.member.enumerated() {

                print("索引:\(indexs)  值:\(item)")

                arrayM.append(item)

            }

          complition(arrayM)

} }

3. viewDidLoad回调函数

var listArr = [Usre]()

override func viewDidLoad() {

        super.viewDidLoad()

        JsonArrModel { (List) in

            self.listArr += List

}

let user = self.listArr[0]

print("\(user.userName) \(user.userEmail) \(user.age)")

}

4.模型类

class Usre: Codable { 

   var userName:String

    var age:String

    var userEmail:String

    init(userName:String,age:String,userEmail:String) {

         self.userEmail = userEmail

        self.userName = userName

        self.age = age}

}

class Department: Codable {

    var name: String

    var id: String

    var member: [Usre

      init(name: String, id: String ,member:[Usre]) {

      self.name = name;

        self.id = id;

        self.member = member;

    }

}
上一篇下一篇

猜你喜欢

热点阅读