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

0

1 Answer 1

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
    }
}

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. Your solution is correct enough. And I found two more)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.