iPhone JSON Parse Problem
I'm working with parsing JSON into my app and am running into some issues pulling in just one section of it. For some reason, it seems to be going through my whole JSON feed, logging NULL values except for the one I specify.
Any advice? Thanks for the help!
My Method:
-(void)loadStats {
NSDictionary *totalsfeed = [self downloadTotals];
NSArray *totals = (NSArray *)[totalsfeed valueForKey:@"totals"];
NSLog(@"NEW TOTALS: %@", [totals valueForKey:@"d_monthly_total"]);
}
Console Results:
2011-08-30 11:35:38.096 App Name [9142:16507] NEW TOTALS: (
"<null>",
"<null>",
2,
"<null>",
"<null>",
"<null>"
)
JSON Feed
{
"totals": [
{
"ab_grand_total": "2217"
},
{
"d_grand_total": "1096"
},
{
"d_monthly_total": "2"
},
{
"ab_monthly_total": "13"
},
{
"ab_yearly_total": "746"
},
{
"d_yearly_total": "233"
}
开发者_如何学运维]
}
I'm parsing the JSON here:
// JSON from Server Actions
- (NSString *)stringWithUrl:(NSURL *)url {
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadRevalidatingCacheData
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
- (id)objectWithUrl:(NSURL *)url {
SBJsonParser *jsonParser = [SBJsonParser new];
NSString *jsonString = [self stringWithUrl:url];
// Parse the JSON into an Object
return [jsonParser objectWithString:jsonString error:NULL];
}
- (NSDictionary *)downloadTotals {
id totals = [self objectWithUrl:[NSURL URLWithString:@"http://example.com/totals.json"]];
NSDictionary *totalsfeed = (NSDictionary *)totals;
return totalsfeed;
}
totals
is an NSArray
of NSDictionary
objects, so [totals valueForKey:@"d_monthly_total"]
does not make sense. Instead, to get d_monthly_total
, you should do:
NSDictionary *dMonthlyTotalDictionary = (NSDictionary *)[totals objectAtIndex:2];
NSLog(@"NEW TOTALS: %@", [dMonthlyTotalDictionary objectForKey:"d_monthly_total"]);
To iterate through totals, do:
for(NSDictionary *myDict in totals) {
for(NSString *key in myDict) {
NSLog(@"%@: %@", key, [myDict objectForKey:key]);
}
}
Don't you have the NSDictionary and NSArray the wrong way around for the JSON you show here - wouldn't you expect the NSArray to be the outer container?
If you can control your JSON feed, you should merge these totals into a single has, e.g.:
{"ab_grand_total": "2217",
"ab_grand_total": "2217",
"d_grand_total": "1096"
}
and then load it as an NSDictionary instead of an NSArray.
精彩评论