在Swift 5,iOS 14中编码可编码结构时发生NSJSONSerialization错误:JSON写入中的顶级类型



我创建了一个简单的结构:

struct CodePair: Codable {
var userId: Int
var code: String
}

我尝试使用以下代码将结构编码为JSON:

let id = 5
let code = "ABCDEF"
let codePair = CodePair(userId: id, code: code)
let json = try? JSONSerialization.data(withJSONObject: codePair)
print(json)

我得到以下错误:

terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
terminating with uncaught exception of type NSException
CoreSimulator 732.17 - Device: iPhone 8 (1ADCB209-E3E6-446F-BC41-3A02B418F7CE) - Runtime: iOS 14.0 (18A372) - DeviceType: iPhone 8

我有几个结构设置几乎相同,但没有一个遇到这个问题。有人知道这里发生了什么吗?

(当然,这是对API的更大异步调用的一部分,但这是有问题的代码。(

您使用了错误的编码器。您应该使用JSONEncoder编码方法,而不是JSONSerialization.data(withJSONObject:)

let id = 5
let code = "ABCDEF"
let codePair = CodePair(userId: id, code: code)
do {
let data = try JSONEncoder().encode(codePair)
print(String(data: data, encoding: .utf8)!)
} catch {
print(error)
}

这将打印:

{"userId":5,"code":"ABCDEF"}

您尝试使用的方法需要字典或数组:

let jsonObject: [String: Any] = ["userId":5,"code":"ABCDEF"]
do {
let jsonData = try JSONSerialization.data(withJSONObject: jsonObject)
print(String(data: jsonData, encoding: .utf8)!)  // {"userId":5,"code":"ABCDEF"}
} catch {
print(error)
}

最新更新