Swift 结构可编码但无法编码
Swift Struct is Codable but can't encode
struct KOTextPrompt: Codable {
let prompt: String
let response: String
}
我有一个非常简单的 Codable 结构。我一直在尝试使用 Alamofire 将其作为参数传递并发生崩溃
2019-07-31 14:52:00.894242-0700 Kirby[8336:1685359] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__SwiftValue)'
我尝试打印下面的代码并得到 "false"。我做错了什么?
let gg = KOTextPrompt(prompt: "testprompt", response: "testresponse")
print(JSONSerialization.isValidJSONObject(gg))
这里的问题是作为 KOTextPromptit
实例的 gg
不是有效的 JSON 对象。您需要对结构进行编码:
struct KOTextPrompt: Codable {
let prompt, response: String
}
let gg = KOTextPrompt(prompt: "testprompt", response: "testresponse")
do {
let data = try JSONEncoder().encode(gg)
print("json string:", String(data: data, encoding: .utf8) ?? "")
let jsonObject = try JSONSerialization.jsonObject(with: data)
print("json object:", jsonObject)
} catch { print(error) }
这将打印
json string: {"response":"testresponse","prompt":"testprompt"}
json
object: {
prompt = testprompt;
response = testresponse; }
struct KOTextPrompt: Codable {
let prompt: String
let response: String
}
我有一个非常简单的 Codable 结构。我一直在尝试使用 Alamofire 将其作为参数传递并发生崩溃
2019-07-31 14:52:00.894242-0700 Kirby[8336:1685359] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__SwiftValue)'
我尝试打印下面的代码并得到 "false"。我做错了什么?
let gg = KOTextPrompt(prompt: "testprompt", response: "testresponse")
print(JSONSerialization.isValidJSONObject(gg))
这里的问题是作为 KOTextPromptit
实例的 gg
不是有效的 JSON 对象。您需要对结构进行编码:
struct KOTextPrompt: Codable {
let prompt, response: String
}
let gg = KOTextPrompt(prompt: "testprompt", response: "testresponse")
do {
let data = try JSONEncoder().encode(gg)
print("json string:", String(data: data, encoding: .utf8) ?? "")
let jsonObject = try JSONSerialization.jsonObject(with: data)
print("json object:", jsonObject)
} catch { print(error) }
这将打印
json string: {"response":"testresponse","prompt":"testprompt"}
json object: { prompt = testprompt; response = testresponse; }