iPhone JSON解析问题

时间:2011-08-30 18:40:38

标签: iphone json

我正在将JSON解析到我的应用程序中,并且遇到了一些问题,只涉及其中一部分。出于某种原因,它似乎正在通过我的整个JSON提要,记录除我指定的值之外的NULL值。

有什么建议吗?谢谢你的帮助!

我的方法:

-(void)loadStats {
NSDictionary *totalsfeed = [self downloadTotals]; 
NSArray *totals = (NSArray *)[totalsfeed valueForKey:@"totals"];  
NSLog(@"NEW TOTALS: %@", [totals valueForKey:@"d_monthly_total"]); 
}

控制台结果:

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"
        }
    ]
}

我在这里解析JSON:

// 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;
    }

3 个答案:

答案 0 :(得分:0)

totalsNSArrayNSDictionary个对象,因此[totals valueForKey:@"d_monthly_total"]没有意义。相反,要获得d_monthly_total,您应该这样做:

NSDictionary *dMonthlyTotalDictionary = (NSDictionary *)[totals objectAtIndex:2];
NSLog(@"NEW TOTALS: %@", [dMonthlyTotalDictionary objectForKey:"d_monthly_total"]);

要遍历总计,请执行:

for(NSDictionary *myDict in totals) {
    for(NSString *key in myDict) {
        NSLog(@"%@: %@", key, [myDict objectForKey:key]);
    }
}

答案 1 :(得分:0)

对于您在此处显示的JSON,您是否有错误的NSDictionary和NSArray方式 - 您不期望NSArray成为外部容器吗?

答案 2 :(得分:0)

如果您可以控制JSON Feed,则应将这些总计合并为一个,例如:

{"ab_grand_total": "2217",
 "ab_grand_total": "2217",
 "d_grand_total": "1096"
}

然后将其加载为NSDictionary而不是NSArray。