Can I minimize the number of objects used in this SBjson code?
The response I receive from the server is formatted as such:
{
"Data":{
"Key": "Value"
...
},
"Key": "Value"
...
}
However, I am开发者_C百科 only interested in the elements under "Data". Here is the code I'm currently using:
SBJsonParser *parser = [SBJsonParser new];
NSString *responseString = [request responseString];
NSDictionary *responseData = [parser objectWithString:responseString];
NSString *infoString = [responseData objectForKey:@"Data"];
NSDictionary *infoData = [parser objectWithString:infoString];
Is there a way to perform the same thing without explicitly declaring 5 objects? Just looking for some sense of short-hand that I should be using.
Your last two lines are wrong - "Data"
is actually an NSDictionary
, so you don't need to double parse it.
Also, most objective-C programmers would nest calls where they know that the returns are safe - by which I mean don't need additional checking. For instance, this would see a more natural implementation to me:
NSDictionary *responseDictionary = [[request responseString] JSONValue];
NSDictionary *infoData = [responseDictionary objectForKey:@"Data"];
Note that I am using the convenience method JSONValue
from the category on NSObject that comes with SBJSON
.
精彩评论