我知道这听起来很复杂,但让我解释一下.
我正在从Web服务获取以下json数据:
{
"code": 200,
"object": {
"id": 1,
"name": "Peter"
}
}
因此,我将其转换为jsonObject,然后希望将该对象"提取"到"Person" struct 中
import Foundation
struct Person : Decodable {
var id : Int
var name : String
}
let data = """
{
"code": 200,
"object": { //this can be any object
"id": 1,
"name": "Peter"
}
}
""".data(using: .utf8)!
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
if json["code"] as! Int == 200 {
var object = json["object"] as! Data
do {
let person = try JSONDecoder().decode(Person.self, from: object)
print(person.name)
} catch { print(error) }
} else {
print("Error")
}
}
} catch { print(error) }
也许有一种更简单的方法可以做到这一点,我不知道我是Swift的新手,我也没有找到很多关于这方面的信息.
如果有任何关于这一程序的建议或 comments ,我将不胜感激.