为什么#Codable#在下面的代码中不起作用? [英] Why #Codable# not working in below code?

查看:119
本文介绍了为什么#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆