You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 4中如何同时支持大小写JSON键的解码?

Got it, this is a super common snag with Swift's Codable system—since JSONDecoder does exact, case-sensitive key matching by default, it chokes when the JSON uses lowercase keys while your struct uses uppercase (or vice versa). Let's walk through two solid solutions to make your Todo struct play nice with both cases.

Method 1: Custom CodingKeys for Per-Struct Case Insensitivity

This is the most straightforward fix if you only need this behavior for your Todo struct. We'll add a custom CodingKeys enum that ignores case when matching JSON keys to your struct properties:

struct Todo: Codable {
    let ID: Int?
    let LAST_DT_ADD: String?
    let LAST_ID: Int?
    
    enum CodingKeys: String, CodingKey {
        case ID
        case LAST_DT_ADD
        case LAST_ID
        
        // Custom initializer to handle case-insensitive key matches
        init?(stringValue: String) {
            let lowercasedKey = stringValue.lowercased()
            switch lowercasedKey {
            case "id":
                self = .ID
            case "last_dt_add":
                self = .LAST_DT_ADD
            case "last_id":
                self = .LAST_ID
            default:
                return nil
            }
        }
        
        // Required by the CodingKey protocol to return our struct's key names
        var stringValue: String {
            switch self {
            case .ID: return "ID"
            case .LAST_DT_ADD: return "LAST_DT_ADD"
            case .LAST_ID: return "LAST_ID"
            }
        }
    }
}

How this works: The custom init?(stringValue:) converts any incoming JSON key to lowercase, then matches it to the lowercase version of our struct's key names. This means JSON keys like id, ID, or even iD will all correctly map to your ID property.

Method 2: Global Case-Insensitive Decoding Strategy

If you have multiple structs that need to handle case-insensitive JSON keys, this approach keeps your code clean and DRY (Don't Repeat Yourself). We'll create a custom key decoding strategy for JSONDecoder that automatically normalizes all JSON keys to match your struct's case:

First, define a reusable custom CodingKey implementation:

private struct CaseInsensitiveCodingKey: CodingKey {
    var stringValue: String
    var intValue: Int?
    
    init?(stringValue: String) {
        self.stringValue = stringValue
        self.intValue = nil
    }
    
    init?(intValue: Int) {
        self.stringValue = String(intValue)
        self.intValue = intValue
    }
}

Then configure your JSONDecoder to use this strategy (we'll normalize JSON keys to uppercase to match your struct's property names):

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom { codingPath in
    guard let lastKey = codingPath.last else {
        fatalError("Failed to retrieve key from coding path")
    }
    // Convert the incoming JSON key to uppercase to match your struct's keys
    let normalizedKey = lastKey.stringValue.uppercased()
    return CaseInsensitiveCodingKey(stringValue: normalizedKey)!
}

Now you can use this decoder with your original Todo struct (no changes needed to the struct itself):

do {
    let todo = try decoder.decode(Todo.self, from: responseData)
    completionHandler(todo, nil)
} catch {
    print("Error decoding JSON: \(error.localizedDescription)")
    completionHandler(nil, error)
}

How this works: Every JSON key gets converted to uppercase before the decoder tries to match it to your struct's properties. This means lowercase keys like id become ID, which perfectly matches your struct's property name. If your struct used lowercase properties instead, just swap uppercased() with lowercased().

Quick Recommendation

  • Use Method 1 if you only need case insensitivity for one or two structs, or if you have special key mapping rules beyond just case.
  • Use Method 2 if you have multiple structs that need this behavior—it saves you from repeating custom CodingKeys everywhere.

内容的提问来源于stack exchange,提问作者Dmitry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:45:36