Last active
June 24, 2017 20:29
-
-
Save takasek/7584f36cd365a495119fd3742590951b to your computer and use it in GitHub Desktop.
JSONのキーが "name" でも "NAME" でも受け入れてくれるDecodable #CodePiece
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func decodeJSON<T: Decodable>(_ t: T.Type, from string: String) { | |
let data = string.data(using: .utf8)! | |
let decoder = JSONDecoder() | |
let s = try! decoder.decode(t, from: data) | |
print(s) | |
} | |
struct Robustness: Decodable { | |
let name: String | |
private enum CodingKeys: CodingKey { | |
case name | |
} | |
private enum NameCodingKeys: String, CodingKey { | |
case lowerName = "name" | |
case upperName = "NAME" | |
} | |
init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: NameCodingKeys.self) | |
name = try container.decodeIfPresent(String.self, forKey: .lowerName) ?? { | |
try container.decode(String.self, forKey: .upperName) | |
}() | |
} | |
} | |
decodeJSON(Robustness.self, from: """ | |
{ | |
"name": "名前", | |
} | |
""") | |
decodeJSON(Robustness.self, from: """ | |
{ | |
"NAME": "名前", | |
} | |
""") | |
//decodeJSON(Robustness.self, from: """ | |
//{ | |
// "name": 1, | |
//} | |
//""") | |
//error: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [Optional(__lldb_expr_21.Robustness.(NameCodingKeys in _4DF6FC7D4401F1058D53C11DCCEEFFE2).lowerName)], debugDescription: "Expected to decode String but found a number instead.")) | |
//decodeJSON(Robustness.self, from: """ | |
//{ | |
// "namae": "名前", | |
//} | |
//""") | |
//error: Swift.DecodingError.keyNotFound(__lldb_expr_5.Robustness.(NameCodingKeys in _2EA1F108365D333F4870AEDC03392B10).upperName, Swift.DecodingError.Context(codingPath: [Optional(__lldb_expr_5.Robustness.(NameCodingKeys in _2EA1F108365D333F4870AEDC03392B10).upperName)], debugDescription: "Key not found when expecting non-optional type String for coding key \"upperName\"")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment