David Park
David Park

Reputation: 325

Swift Struct is Codable but can't encode

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

I have a very simple struct that is Codable. I'm been trying to pass this as a parameter using Alamofire and got a crash

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)'

I tried printing the code below and got "false". What am I doing wrong?

let gg = KOTextPrompt(prompt: "testprompt", response: "testresponse")
        print(JSONSerialization.isValidJSONObject(gg))

Upvotes: 0

Views: 285

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236568

The issue here is that gg which is an instance of KOTextPromptit is not a valid JSON object. You need to encode your struct:

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) }

This will print

json string: {"response":"testresponse","prompt":"testprompt"}

json object: { prompt = testprompt; response = testresponse; }

Upvotes: 2

Related Questions