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

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

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

3e66b3ccfa617b78c59d9dec865aa29f?s=128

noppefoxwolf

October 16, 2018
Tweet

More Decks by noppefoxwolf

Other Decks in Programming

Transcript

  1. $PEBCMFͰΧΦεͳ+40/ ʹରԠ͍ͯ͘͠ 0UFNBDIJTXJGUOPQQF !OPQQFGPYXPMG 

  2. OPQQF ! σΟʔɾΤψɾΤʔ " ϥΠϒ഑৴J04ΞϓϦ # ͖ͭͶ͔Θ͍͍ $ 0UFNBDIJTXJGUॳࢀઓ 

  3. ελϯμʔυͳ+40/ 

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

    = JSONDecoder() let userData = try decoder.decode(Response.self, data: data) 
  5. ੈͷதʹ͸ΧΦεͳ+40/͕͋Δ ࠓ೔͸̎ͭ঺հ 

  6. ࣄྫ 

  7. ͜ͷ+40/Կ͕͓͔͍͠Ͱ͔͢ 

  8. TOBLF@DBTFͱLFCBC DBTF͕ࠞ߹͍ͯ͠Δʂ 

  9. TOBLF@DBTFҎ֎͕ࠞͬ͟ ͍ͯΔͱ ,FZ%FDPEJOH4USBUFHZ͕ ࢖͑ͳ͍ʜ 

  10. ,FZ%FDPEJOH4USBUFHZͱ͸ʁ 4XJGUʙ +40/Ωʔ໊ϓϩύςΟ໊ͷϧʔϧΛࢦఆ ͢ΔࣄͰɺCodingKey΍init(from decoder:)Λ࣮૷ͤͣʹϚοϐϯάग़དྷΔ 

  11. ,FZ%FDPEJOH4USBUFHZͱ͸ʁ let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let obj

    = try decoder.decode(Response.self, from: data) 
  12. େৎ෉ 

  13. ΧελϜσίʔυϧʔϧ decoder.keyDecodingStrategy = .custom { keys in let lastComponent =

    keys.last!.stringValue.camelCase return AnyKey(stringValue: String(lastComponent))! } ΧελϜͳLFZ%FDPEJOH4USBUFHZΛ࡞Δࣄ ͕Ͱ͖Δɻ 
  14. 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() } } 
  15. ࣄྫ̎ 

  16. ͜ͷ+40/Կ͕͓͔͍͠Ͱ͔͢ 

  17. 

  18. ܕ͕ෆఆ 

  19. ܕ͕ෆఆ w Ұճ"OZʹ٧ΊͯɺऔΓग़࣌͢ʹܕΛ෇͚ ͯ͋͛Δ w ଘࡏ͠͏Δ͢΂ͯͷϑΟʔϧυΛ࣋ͬͨΦ ϒδΣΫτʹϚοϐϯά͢Δ w %JDUJPOBSZͰ࣋ͭ 

  20. ܕ͕ෆఆ 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() } } } 
  21. ܕ͕ෆఆ ࢖͏ͱ͖͸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 } 
  22. ! ͳΜ͔ଞʹྑ͍ํ๏͕͋Δؾ͕͢ΔͷͰɺ ஌͍ͬͯΔਓ͕͍ͨΒڭ͍͑ͯͩ͘͞ 

  23. ͦ΋ͦ΋ ͳΜͰ͜ΜͳKTPOύʔεͯ͠Δͷʁʁ 

  24. HBCBJ "1*ΫϥΠΞϯτϥΠϒϥϦΛ࡞ͬͯ·͢ 

  25. OPQQFGPYXPMG(BC,JU ࠓճͷςΫχοΫͰ࣮૷ͯ͠·͢ HBC·ͩ·ͩ೔ຊਓগͳ͍ͷͰɺڵຯ͋Δਓ ͸࢖ͬͯΈ͍ͯͩ͘͞ʙʙ 

  26. $JSPOOVQνψϩοϓ HBCDPNͷJ04ωΠςΟϒΞϓϦɻ৹ࠪத 

  27. ͋Γ͕ͱ͏͍͟͝·ͨ͠