json - swift 4 - 具有树结构的 json 解码对象
问题描述
我想解码我的用户 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?
}
推荐阅读
- javascript - 选择在 ajax 自动完成中显示未定义的部分
- package - R管道工和jsonlite包冲突
- c++ - 观察者模式(C++):将模板类从子类转换为模板的基类
- ios - CountdownLabel 检查是否完成
- c# - 如何使用 AmazonS3EncryptionClientV2 客户端加密从 AWS S3 存储桶下载对象?
- scala - 在案例类上定义+操作
- python-3.x - 需要帮助来理解错误。我已经尝试过类似的帖子
- angular - 功能模块中的角度对话框引发错误“mat-dialog-content”不是已知元素
- java - Spring-MVC CRUD项目静态方法错误
- javascript - Mocha - 复选标记 √ 在 Git Bash 上打印为 ΓêÜ