views:

21

answers:

1

Hi all,

I have JSON data being provided to my application but unfortunatly it is not very well formed. Sometimes I am getting 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

+1  A: 

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

Justin
Thanks. I forgot to mention that I am currently using 'intValue' on the objects descritpion method as a work around. I was just hoping I had missed a more convenient method. I managed to get the JSON provider to fix some of the issues with the JSON at source but I was hoping for a easy way for error recovery.
James T