I am trying to build a parser/objectMapper that will build Objective C objects for the JSON I consume from a REST service.
I took some inspiration from RestKit by having
I tried the same approach also. My main problem was, to describe the types accurately. For example for nested arrays I used something like this:
@{ @"friends" : @[[Person class]] }
But things became messy, because I needed to invent more and more special syntax for different types, that I wanted to support. In the end I stopped pursuing this approach and went for another solution - also because the runtime checks I needed to do were slowing the transformation down.
There are a lot of solutions out there right now. I would suggest to have a look at Awesome iOS website. And I also would like to point out JSON Class Generator, because it allows you to
I hate to advertise, but this tool saved me a lot of work, that I invested into other features of my apps. It came out a little late, now that the world seems to switch to Swift, but even more reason to not waste time on writing models in Objective-C.
Here are some code examples converting to/form JSON:
// converting MyClass <-> NSDictionary
MyClass *myClass = [MyClass myClassWithDict:someJsonDictionary];
NSDictionary *jsonDict = [myClass toDict];
// converting NSDictionary <-> NSData
NSDictionary *someJsonDictionary = [NSDictionary api_dictionaryWithJson:someJsonData];
NSData *jsonData = [someJsonDictionary api_toJson];
The features mentioned in a previous comment are also supported by JSON Class Generator:
-isEqual, -hash, -description, -copy, NSCoding/NSSecureCoding/NSKeyedArchiver
support for free and does check for missing/additional/NSNull/optional fields and wrong types in the JSON response, reports errors, gracefully fails with fallback values and does this using method dispatch rather than runtime type introspection (which is faster).