[英]iPhone JSON Parse Problem
我正在将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;
}
totals
是NSDictionary
对象的NSArray
,因此[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]);
}
}
您是否对NSDictionary和NSArray使用了此处显示的JSON错误的方式-您是否希望NSArray成为外部容器?
如果可以控制JSON提要,则应将这些总计合并到单个has中,例如:
{"ab_grand_total": "2217",
"ab_grand_total": "2217",
"d_grand_total": "1096"
}
然后将其作为NSDictionary而不是NSArray加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.