[英]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.