我被困在如何解析一个属性化的 JSON 对象上。我设法解析 JSON 对象并得到一个整洁的NSDictionary
,但是我将属性作为@"xxx"
文本.. 这不是可取的。
我猜它与我有关options:kNilOptions
,但我找不到它应该是什么。
这是 JSON 对象:
{
"sport": [
{
"@description": "Fotboll",
"@id": "1",
"@name": "SOCCER"
},
{
"@description": "Ishockey",
"@id": "2",
"@name": "HOCKEY"
}
]
}
这是我的结果字典:
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;
}
);
}
这是我的代码:
-(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];
}
我想作为结果字典得到什么:
{
sport = (
{
"description" = Fotboll;
"id" = 1;
"name" = SOCCER;
},
{
"description" = Ishockey;
"id" = 2;
"name" = HOCKEY;
}
);
}