简体   繁体   English

迅捷4-json解码具有树结构的对象

[英]swift 4 - json decode object with tree structure

I want to decode my user json object, but I have my difficulties with decoding the superior object. 我想解码我的用户json对象,但是在解码上级对象时遇到了困难。 The superior object is just another user that stands above the user. 上级对象只是站在该用户上方的另一个用户。 The structure looks like this 结构看起来像这样

   {
       "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()
    }

When I set the type of superior to "UserStructure?" 当我将上级类型设置为“ UserStructure?”时 I get the error "Value Type 'UserStructure" cannot have a stored property that recursively contains it. 我收到错误“值类型'UserStructure”不能具有递归包含它的存储属性。 I thought about creating a SuperiorStructure but then I would have the same problem a step further. 我曾考虑过创建SuperiorStructure,但接下来我将遇到同样的问题。

Like the compiler error message says, structs cannot have properties that contain an instance of themselves. 就像编译器错误消息所说的那样,结构不能具有包含其自身实例的属性。 Use class in this case: 在这种情况下使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM