简体   繁体   中英

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. 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?" I get the error "Value Type 'UserStructure" cannot have a stored property that recursively contains it. I thought about creating a SuperiorStructure but then I would have the same problem a step further.

Like the compiler error message says, structs cannot have properties that contain an instance of themselves. Use class in this case:

class UserStructure: Decodable {
   var id: Int64?
   var username: String?
   var email: String?
   var userFunction: UserFunctionStructure?
   var password: String?
   var superior: UserStructure?
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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