Swift Struct是可编码的,但无法编码

时间:2019-07-31 21:59:14

标签: swift encoding alamofire decoding codable

struct KOTextPrompt: Codable {
    let prompt: String
    let response: String
}

我有一个非常简单的可编码结构。我一直在尝试使用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))

1 个答案:

答案 0 :(得分:2)

这里的问题是gg的实例KOTextPromptit不是有效的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字符串:{“ response”:“ testresponse”,“ prompt”:“ testprompt”}

     

json   对象:{       提示=测试提示;       响应=测试响应; }