[swift-evolution] Support for a KeyCodingStrategy option in JSONEncoder and JSONDecoder

Mike Kluev mike.kluev at gmail.com
Mon Oct 23 05:19:10 CDT 2017


on 19 Oct 2017 11:21:39 -0700 Eagle Offshore <eagleoffshore at mac.com> wrote:

Yes, in general, I think Codable is a poor solution for json decoding just
> like I never used NSCoding to convert JSON to and from objects.  It feels
> clumsy.
>
> I found it a much better solution to add a category to NSObject that had
>
> -(NSData*)toJSONRepresentationWithMappings:(NSDictionary*)d
> +()fromJSONRepresentation:(NSData*) mappings:(NSDictionary*)d
>
> where mappings might be { @"firstName": @"first_name", etc.... }
>
> and was simple to write a general solution using introspection and KVC.
>
> Codable is a limited one trick pony that would be trivial to write as a
> trait or extension if Swift provided the more profound thing -
> introspection and reflection.  A whole world of opportunities would open up
> with that and we could stop wasting time on Codable and KeyPath - neither
> of which is that useful when working with string data from the wild.
>

i found Codable very useful. when you need to translate the keys it's a bit
awkward and looks "unfinished" but if you don't need the translation you
literally write no code at all which is good.

having Codable does not contradict having introspection /
reflection. general (or shall we say custom) approaches that use
introspection / reflection tend to work much slower (from Objective-C
experience). i have no data if Codable is performant in these regards but
at least it has a potential to be more optimal than a general solution
based on introspection / reflection.

Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171023/982d8040/attachment.html>


More information about the swift-evolution mailing list