这是我的JSON
{
"id": 1,
"user": {
"user_name": "Tester",
"real_info": {
"full_name":"Jon Doe"
}
},
"reviews_count": [
{
"count": 4
}
]
}
Run Code Online (Sandbox Code Playgroud)
这是我想要保存的结构(不完整)
struct ServerResponse: Decodable {
var id: String
var username: String
var fullName: String
var reviewCount: Int
enum CodingKeys: String, CodingKey {
case id,
// How do i get nested values?
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试实现新Codable协议,所以我添加Codable到我的结构中,但我坚持解码JSON.
这是我以前的所作所为:
结构 -
struct Question {
var title: String
var answer: Int
var question: Int
}
Run Code Online (Sandbox Code Playgroud)
客户 -
...
guard let data = data else {
return
}
do {
self.jsonResponse = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
let questionItems = self.jsonResponse?["themes"] as! [[String: Any]]
questionItems.forEach {
let item = Question(title: $0["title"] as! String,
answer: $0["answer"] as! Int,
question: $0["question"] as! Int)
questionData.append(item)
}
} catch {
print("error")
}
Run Code Online (Sandbox Code Playgroud)
这就是我现在所拥有的,除了我无法弄清楚解码器部分:
结构 …
试图弄清楚如何在调试时从 API 漂亮打印我的响应的 json 值:
let session = URLSession(configuration: .default)
let task = session.dataTask(with: urlRequest) { data, response, error in
completion(data, response, error)
}
Run Code Online (Sandbox Code Playgroud)
在调试器中,如果我做 po 数据,这就是我得到的东西:
如何打印出数据对象中的实际 json 结构?希望看到这样的事情:
{ "firstName": "John", "lastName": "Doe", ... }
po debugPrint(data) 在这种情况下不输出任何内容。