I have JSON data being provided to my application but unfortunatly it is not very well formed. Sometimes I am gett开发者_运维百科ing String representations of numbers when I am expecting numbers.
For some reason some values may have a prefix of whitespace.
What is the best way to deal with this? Currently I am forced to check the types via 'isKindOfClass' but having recently worked mainly on python applications this seems awkward.
Can anyone recommend a better way to do this? I am fully aware that @try,@catch etc are not useful in this situation.
Thanks for your help guys, I know this question is being flagged as subjective but I would appreciate some input!
J
first: try really hard to get data which is well-formed. there are too many corner cases, and the process is computationally slow for any nontrivial json request - not to mention the wasted network bandwidth, parsing, etc.. it's a maintenance nightmare.
second: NSString and NSNumber share some convenience methods intValue
, doubleValue
. those will help in some of your cases.
third: if you have a lot of weird stuff, it's probably going to be best to create your own category methods. for example:
@interface NSString (MONEvilJSONSource)
- (int)ejs_intValue;
- (NSDate *)ejs_dateValue;
- (double)ejs_doubleValueForPropertyNamed_Millimeters;
@end
@interface NSNumber (MONEvilJSONSource)
- (int)ejs_intValue;
- (NSDate *)ejs_dateValue;
@end
hope that helps
精彩评论