NSJSON在Swift 5、iOS 14 中对可编码结构进行编码时出现序列化错误:JSON 写入中的顶级类型无效

NSJSONSerialization error when encoding encodable struct in Swift 5, iOS 14: Invalid top-level type in JSON write

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

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

我有几个几乎完全相同的结构设置,其中 none 个遇到了这个问题。有人知道这里发生了什么吗?

(当然,这是对 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)
}