I am stuck on how to parse an attributed JSON object. I manage to parse the JSON object and get a neat NSDictionary
, however I get attributes as @"xxx"
texts.. which is not preferable.
I am guessing it has to do with me options:kNilOptions
but I can't find what it should be.
This is the JSON object:
{
"sport": [
{
"@description": "Fotboll",
"@id": "1",
"@name": "SOCCER"
},
{
"@description": "Ishockey",
"@id": "2",
"@name": "HOCKEY"
}
]
}
This is my result dictionary:
2013-08-26 22:46:44.461 OddsApp[21971:70b] __50-[GetSportsService getSportsOnCompletion:onError:]_block_invoke [Line 43] JSON:
{
sport = (
{
"@description" = Fotboll;
"@id" = 1;
"@name" = SOCCER;
},
{
"@description" = Ishockey;
"@id" = 2;
"@name" = HOCKEY;
}
);
}
This is my code:
-(void)getSportsOnCompletion:(void (^)(NSArray *sports))completionBlock onError:(MKNKErrorBlock)errorBlock
{
[self addCompletionHandler:^(MKNetworkOperation *completedOperation) {
DLog(@"%@: %@", [completedOperation isCachedResponse] ? @"Cache" : @"Response", [completedOperation responseString]);
NSError *err = nil;
id json = [NSJSONSerialization JSONObjectWithData:[completedOperation responseData]
options:kNilOptions
error:&err];
if(err)
{
errorBlock(err);
return;
}
DLog(@"JSON: \n%@", json);
NSArray *array = [(NSDictionary *)json objectForKey:@"sport"];
NSMutableArray *sports = [NSMutableArray arrayWithCapacity:array.count];
for(NSDictionary *item in array) {
[sports addObject:[Sport instanceFromDictionary:item]];
}
completionBlock([NSArray arrayWithArray:sports]);
} errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
errorBlock(error);
}];
[ApplicationDelegate.networkEngine enqueueOperation:self forceReload:YES];
}
What I would like to get as result dictionary:
{
sport = (
{
"description" = Fotboll;
"id" = 1;
"name" = SOCCER;
},
{
"description" = Ishockey;
"id" = 2;
"name" = HOCKEY;
}
);
}
The parser is perfectly fine. You are right, it may be the result of an XML conversion, see for example "Converting Between XML and JSON".
If the parser would simply drop the leading '@' there would be no way to convert the JSON back to XML (since the conversion process is designed to be reversible), so you have to access an attribute by node[@"@name"]
and a child by node[@"name"]
If, in the future, the service changes from attributes to nodes you have to adapt your code. But that's true for every format change...