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

       // 模型转 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)( 字典转 模型))