Search code examples
jsonswiftswift5jsondecoder

Swift 5 JSONDecoder decode JSON with field name having a space eg "post title": "Hello World"


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!


Solution

  • 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.