A lot of modern programming languages have JSON libraries that support encoding and decoding json to/from "plain old objects" - i.e. instances of classes that primarily just have data properties (properties can either be types that can be trivially de/encoded or other plain old objects). Examples include Google's GSON, golang's encoding/json and others.
Is there something similar to Objective-C?
I know that it is possible to enumerate properties for Objective-C classes, and it seems reasonable that someone would have used that capability to create a JSON "bean mapper", but Google searching yielded no results for me, except this blog post on Apple's Swift website showing how to manually deserialize JSON to "model objects" and why they think that doing this automatically (DRYing the code) is a bad idea (*).
*) The reasoning is basically, that not needing to write a lot of boilerplate (their sample implementation is 36 LoC to parse 3 properties) is not a significant improvement and building a couple of optional callbacks to allow data validation is hard. I obviously disagree with all of this.
Here is my solution, which is not based on a library - as I couldn't find any - but instead using the Foundation and Objective-C runtime methods - as discussed in the comments above:
It is then easy to create custom model objects by inheriting from
JSONMarshallable, like so:model.h:model.m:SomeThingElse.m:Critics are welcome! (I'm not very good at Objective C and probably made a lot of faux pas )
Issues:
NSNumber*(though C primitives work fine for non-nullable numbers), but I don't know how to represent nullable booleans - i.e. a field that is optional and not encoded when usingwithNullValues:NO.Sending fields for which there are no properties (for example, the server I work with sends values in both snake-case and underscrore-case to make it easy to parse) throws exception.(solved by usingrespondsToSelector:andsetValue:instead ofsetValuesForKeysWithDictionary:).Trying to set(solved by checking for property type andnilvalues to primitive-typed fields causes exceptions.NSNull).Doesn't work at all for nesting objects - i.e. a custom model object with properties that are also custom model objects.(solved by checking for property types and recursing encoding/decoding).