0

I have two different JSON's, but they are similar. Both JSON have similar keys, but in the first JSON key with lowercase and in the second JSON the same key with uppercase. How can I parse it in the one structure in SWIFT? Example: key in first JSON "gps_x", key in second JSON "GPS_X".

1 Answers1

1

You could use a custom decoding strategy that normalizes your keys into lowercased values:


let jsonData = """
[
 {
    "gps_x" : "test"
 },
 {
    "GPS_x" : "test2"
 }
]
""".data(using: .utf8)!

struct GPSNormalized : Decodable {
    var gps_x : String
}

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom { keys in
    let normalized = keys.last!.stringValue
    return AnyKey(stringValue: normalized.lowercased())!
}

do {
    print(try decoder.decode([GPSNormalized].self, from: jsonData))
} catch {
    print(error)
}

struct AnyKey: 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
    }
}

jnpdx
  • 45,847
  • 6
  • 64
  • 94