[英]swift 4 - json decode object with tree structure
我想解码我的用户json对象,但是在解码上级对象时遇到了困难。 上级对象只是站在该用户上方的另一个用户。 结构看起来像这样
{
"id": 3,
"username": "a",
"email": "a@abc.com",
"userFunction": "4",
"password": "****",
"superior": {
"id": 2,
"username": "b",
"email": "b@abc.com",
"userFunction": "3",
"password": "****",
"superior": {
"id": 1,
"username": "c",
"email": "c@abc.com",
"userFunction": "1",
"password": "****",
"superior": null,
},
},
}
struct UserStructure: Decodable {
var id: Int64?
var username: String?
var email: String?
var userFunction: UserFunctionStructure?
var password: String?
var superior: UserStructure?
}
func fetchUser(username: String){
let urlString = "http://localhost:8080/rest/user/" + username
let url = URL(string: urlString)!
URLSession.shared.dataTask(with: url) { (data, response, error) -> Void in
if error != nil {
print(error!)
return
}
guard let data = data else {
return
}
do {
let user = try JSONDecoder().decode(UserStructure.self, from: data)
print(user)
} catch let err {
print(err)
}
}.resume()
}
当我将上级类型设置为“ UserStructure?”时 我收到错误“值类型'UserStructure”不能具有递归包含它的存储属性。 我曾考虑过创建SuperiorStructure,但接下来我将遇到同样的问题。
就像编译器错误消息所说的那样,结构不能具有包含其自身实例的属性。 在这种情况下使用class
:
class UserStructure: Decodable {
var id: Int64?
var username: String?
var email: String?
var userFunction: UserFunctionStructure?
var password: String?
var superior: UserStructure?
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.