Swift Json with hyphens

(Swift, macOS, storyboards)

//I have a JSON in a URL. Simplified it is something like this:
{
    "id": 1,
    "name": "Leanne Graham",
    "with-hyphen": 123
}

//Outside the class ViewController:
struct User: Codable {
    let id: Int
    let name: String
    let with: Int
}

//In the class ViewController:
    @IBAction func getJson(_ sender: NSButton) {
        let url = URL(string: "https://example.com")!
        URLSession.shared.dataTask(with: url) { data, _, _ in
            if let data = data {
                let result = try? JSONDecoder().decode(User.self, from: data)
                //let result2 = result!.name //it works
                //let result3 = result!.with-hyphen //it does not work
                //print (result3)
            }
        }.resume()
    }

I can safe in a let the regular "id" and "name" but I do not know how to deal with the keys with hyphens, in the example: "with-hyphen"

Accepted Reply

You cannot have hyphens in names.

The best is to use CodingKeys.

struct User: Codable {
    let id: Int
    let name: String
    let withHyphen: Int

    enum CodingKeys : String, CodingKey {
        case id = "id"
        case name = "name"
        case withHyphen = "with-hyphen"
    }
}

Then call:

let result2 = result!.name 
let result3 = result!.withHyphen 

Avoid using with, it is a reserved word.

Replies

You cannot have hyphens in names.

The best is to use CodingKeys.

struct User: Codable {
    let id: Int
    let name: String
    let withHyphen: Int

    enum CodingKeys : String, CodingKey {
        case id = "id"
        case name = "name"
        case withHyphen = "with-hyphen"
    }
}

Then call:

let result2 = result!.name 
let result3 = result!.withHyphen 

Avoid using with, it is a reserved word.