never!
- json ... is nil ...
- EXC_BAD_ACCESS
- ... unrecognized selector ... [NSString boolValue]
- ... index out of bounds ...
Pros & Cons
• very quick code turnaround!!!
• no structure validation
• no data validation
• difficult to error handle
• it’s the road to maintenance
HELL!
evolution indicator
A better way!
NSDictionary* json = [NSJSONSerialization ... ];
if (json == nil) [self errorHandleEmptyJSON];
if (json[@”name”] == nil)
[self errorHandleEmptyName];
NSArray* name = json[@”name”];
if (name.count<1]
[self errorHandleWrongJSONStructure];
NSNumber* value = name[1][2][@”value”];
Forget much? oh noes...
Looks good so far, what’s left?
- validate the data for all values you use
- check if the incoming objects are of the
expected class type (yuicks!)
- make sure you decend into the JSON
according to the incoming structure
Pros & cons?
• Horribly slow to write code
• Difficult to maintain
• How do you recover from errors
in the middle of the parsing process???
• Better data validation
• Better structure validation
evolution indicator
Data models?
The “M” in MVC stands
for “MODEL”
Wrap up all the code in
classes for all your models
feels good!
Your models feature custom init
which reads the JSON and builds
up the model representation
All IF statements and all the error
handling is handled within the
model class
Other magic you coded at 4.17am on a Thursday
Pros & cons
• Using a class instead of NSDictionary
• OOP 4 Ever!
• Very flexible code
• Lot of redundant parsing code
• Lot of implementation
• Still harder to adapt to changes
evolution indicator
Then what?
Throughout 2012 I worked
mainly on JSON powered
applications.
In December I was already
fed-up with:
self.name = json[@”name”];
Eureka!
JSONModel
- import JSON
- structure validation
- data type validation
- data type conversion
- atomic operations
- error handling
Automatically does/has:
Import JSON
.h .m
For relatively simple models eliminates
the need to code in your .m file
Conversion
@property (strong, nonatomic) NSURL* blogSiteUrl;
What you want is:
What you get is:
{“blogSiteUrl”:“http://www.yahoo.com”}
It is about what you want to have!