Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CodableでカオスなJSONに対応していく/Otemachi02

 CodableでカオスなJSONに対応していく/Otemachi02

noppefoxwolf

October 16, 2018
Tweet

More Decks by noppefoxwolf

Other Decks in Programming

Transcript

  1. $PEBCMFͰϚοϐϯά struct UserData { let id: String } let decoder

    = JSONDecoder() let userData = try decoder.decode(Response.self, data: data) 
  2. ΧελϜσίʔυϧʔϧ decoder.keyDecodingStrategy = .custom { keys in let lastComponent =

    keys.last!.stringValue.camelCase return AnyKey(stringValue: String(lastComponent))! } ΧελϜͳLFZ%FDPEJOH4USBUFHZΛ࡞Δࣄ ͕Ͱ͖Δɻ 
  3. TOBLF@DBTFPSLFCBCDBTFUP DBNFM$BTF extension String { internal var camelCase: String {

    return self.replacingOccurrences(of: "-", with: "_") .components(separatedBy: "_") .enumerated() .map { 0 == $0 ? $1 : $1.capitalized } .joined() } } 
  4. 

  5. ܕ͕ෆఆ struct AttachmentObject: Decodable { let value: Any init(from decoder:

    Decoder) throws { let container = try decoder.singleValueContainer() if let value = try? container.decode(Media.self) { self.value = value } else if let value = try? container.decode([Media].self) { self.value = value } else { preconditionFailure() } } } 
  6. ܕ͕ෆఆ ࢖͏ͱ͖͸TXJUDIͳͲͰ෼ذ switch object.data.value { case let value as Media:

    print(value.id) case let value as [Media]: print(value.compactMap({ $0.id })) default: break }