Swift 4 JSONEncoder 不能对 String 或 Int 进行编码,但它们遵循 Codable 协议(protocol)

标签 swift jsonencoder

let encoder = JSONEncoder()

do {
   let encodData = try encoder.encode("test string") // same as Int type
   print(encodData) // nil
} catch let err {
   print(err.localizedDescription) // The data couldn’t be written because it isn’t in the correct format.
}

如何编码这些类型值

最佳答案

顶级(根)JSON 对象只能是数组或字典。例如:

do {
    let encoder = JSONEncoder()
    let encodData = try encoder.encode(["test string"])
    print(String(data: encodData, encoding: .utf8)!) 
    // ["test string"]

} catch {
    print(error.localizedDescription)
}

关于Swift 4 JSONEncoder 不能对 String 或 Int 进行编码,但它们遵循 Codable 协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49668246/

相关文章:

ios - 在 MVVM 和 MVC 模式中在哪里创建 View ?

swift - 根据 TableView 中的项目数使动态 UI 按钮出现和消失

ios - 关闭 viewController 后更新 outlets

swift - 获取通用类型 T 的名称作为 String

swift - UIBarButtonItem 值(forKey : key) cannot get view any more

json - Swift:内部数据类型变量通过 JSONEncoder 编码。如何正确反序列化它?

swift - 是否可以仅为枚举创建自定义 Swift KeyEncodingStrategy?

ios - Alamofire JSON 编码 bool 问题?

swift - 在 Swift 中对继承自 Codable 的类进行子类化导致的崩溃

amazon-web-services - Terraform 模板 jsonencoding 与 iterate