美文网首页
(json 转 模型) ( 模型转 json)( 字典转 模型)

(json 转 模型) ( 模型转 json)( 字典转 模型)

作者: 奔跑吧小蚂蚁 | 来源:发表于2022-10-30 18:05 被阅读0次
       // 模型转 json
       let person = Person(name: "张三", age: 34, subs: [Sub(name: "张小六")])
        let encoder = JSONEncoder()
        let data = try! encoder.encode(person)
        let encodedString = String(data: data, encoding: .utf8)!
        print(encodedString)
        // json 转 模型
        let jsonData = encodedString.data(using: .utf8)!
        let decoder = JSONDecoder()
        let result = try! decoder.decode(Person.self, from: jsonData)
        print(result)

        // 字典转 模型
        let body: [String: Any] = [
            "name":"张三",
            "age":  10,
            "disciplines":  [["name": "语文"]]
        ]
        let bodyData: Data! = try? JSONSerialization.data(withJSONObject: body, options: [])
        let bodyDecoder = JSONDecoder()
        let bodyResult = try! bodyDecoder.decode(Student.self, from: bodyData)
        print(bodyResult)

https://blog.csdn.net/sun6223508/article/details/95042887

相关文章

网友评论

      本文标题:(json 转 模型) ( 模型转 json)( 字典转 模型)

      本文链接:https://www.haomeiwen.com/subject/gjjltdtx.html