Note that there are some explanatory texts on larger screens.

plurals
  1. PODetect Missing JSON Keys With Nested Objects
    text
    copied!<p>Currently I am in the process of working with an API that is still in development. Due to this, the keys in the response are still changing. I have successfully been able to retrieve and parse the JSON data from the API into an NSDictionary, and then use this NSDictionary to map the values into custom objects. The approach I am using is the following </p> <pre><code>-(id)initWithDictionary:(NSDictionary*)dictionary { if(self = [super init]){ _ID = [dictionary valueForKey:kKEY_ID]; _name = [dictionary valueForKey:kKEY_NAME]; _nestedObject = [[NestedObject alloc]initWithDictionary:[dictionary valueForKey:kKEY_NESTED_OBJECT]]; //etc... } return self } </code></pre> <p>Each nested object also contains the same parsing structure.</p> <p>This works fine except for when the API changes. When something does change, required values do not exist and this causes unexpected behavior or crashes. </p> <p>Ideally, if one of the keys change, I would like to produce a NSError that I can use to print the value that has changed helping me more quickly find the change and rectify it. </p> <p>The only alternative approach that I have currently been able to come up with I feel is messy and unmaintainable. </p> <pre><code>-(id)initWithDictionary:(NSDictionary*)dictionary andError:(NSError**)error { if(self = [super init]){ BOOL _parsedSuccessfully = TRUE; if (_parsedSuccessfully) { _ID = [dictionary valueForKey: kKEY_ID]; if (!_ID){ _parsedSuccessfully = FALSE; *error = [NSError parsingErrorFromKey: kKEY_ID]; } } if (_parsedSuccessfully) { _name = [dictionary valueForKey: kKEY_NAME]; if (!_name){ _parsedSuccessfully = FALSE; *error = [NSError parsingErrorFromKey: kKEY_NAME]; } } if (_parsedSuccessfully) { _nestedObject = [[NestedObject alloc]initWithDictionary:[dictionary valueForKey:kKEY_NESTED_OBJECT]]; if (!_nestedObject){ _parsedSuccessfully = FALSE; *error = [NSError parsingErrorFromKey: kKEY_NESTED_OBJECT]; } } //etc... if (!_parsedSuccessfully) { return nil; } } return self } </code></pre> <p>I was wondering if anyone else had any other better approaches that preferably uses much less duplication. </p> <p>Any help would be greatly appreciated. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload