1

I'm currently using JSONDecoder to parse json into objects with Swift 5. I'm just realizing now that part of the JSON is bad JSON. It has a field name with a space: "Post Title". I'm not sure why it is like this, and I'm aware it is bad practice for JSON to be setup like this, but there's not much I can do on the JSON side. Is there a way to use JSON decoder to get that field as is?

I've researched this a ton, but since it is an issue with bad json, I'm not finding much online other than creating a custom decoder/deserializer (which I'm trying to avoid).

JSON:

{
    "Post Title":"Hello World"
}

Struct:

struct Post: Decodable {
    var PostTitle: String
}

Decoder:

let jsonObject = try jsonDecoder.decode(Post.self, from: responseData)

Thank you in advance!

voo_doo_juju
  • 61
  • 1
  • 8

1 Answers1

12

For custom keys, use CodingKeys to match JSON keys.

struct Post : Codable {

    var PostTitle: String

    private enum CodingKeys : String, CodingKey {
        case PostTitle = "Post Title"
    }
}

Note: you should use lowercased starting letter for variables.

Gustavo Vollbrecht
  • 3,188
  • 2
  • 19
  • 37