为什么#Codable#在下面的代码中不起作用? [英] Why #Codable# not working in below code?
本文介绍了为什么#Codable#在下面的代码中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码来测试Codable
协议和JSONDecoder
.
I have below code to test Codable
protocol and JSONDecoder
.
import UIKit
class ClassA: Codable {
var age: Int = 1
}
class ClassB: Codable {
var ageInfo: ClassA?
var name: String
}
let json4 = """
{
"ageInfo": {},
"name": "Jack"
}
""".data(using: .utf8)!
do {
let d = try JSONDecoder().decode(ClassB.self, from: json4)
} catch let err {
print(err)
}
我的问题是,为什么 json4 无法解码?或如何解码 json4 ?
My question is, why json4 can't be decode? or how I can decode json4?
推荐答案
您的ClassB具有此功能:
Your ClassB has this:
var ageInfo: ClassA?
但这不能帮助您使用此JSON:
But that doesn’t help you with this JSON:
"ageInfo": {}
问题是ageInfo
存在 ,但它也是空词典.因此,有 个ClassA,但它与您对ClassA的定义不符!
The problem is that ageInfo
is present but it is also an empty dictionary. So there is a ClassA but it doesn't correspond to your definition of ClassA!
更改
class ClassA: Codable {
var age: Int = 1
}
到
class ClassA: Codable {
var age: Int? = 1
}
这篇关于为什么#Codable#在下面的代码中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文