我能够从我的 API 中检索整个 JSON 响应并将其存储在 NSArray 中。
然后我遍历整个响应并将每个结果组存储在 NSDictionary 和 NSLogit 中。
但是,我不是如何从每个组中获取字段值,例如
STNAME,
CTYNAME,
DENSITY,
POP,
DATE,
state,
county
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSArray* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
for (int i=0; i<[json count]; i++) {
NSDictionary *avatars = [json objectAtIndex:i];
NSLog(@"value at %d, ::: %@", i,avatars);
}
我想做的是得到类似的东西
// NSString *name = avatar[@"STNAME"]; // for any specific state or county name..like objectbyKey
这样我就可以从 sep 组中获取每个值。
这就是我的 JSON 数据在 NSLog 上的样子
2014-06-23 12:04:06.893 KivaJSONDemo[2693:90b] value at 0, ::: (
STNAME,
CTYNAME,
DENSITY,
POP,
DATE,
state,
county
)
2014-06-23 12:04:06.894 KivaJSONDemo[2693:90b] value at 1, ::: (
Florida,
"Alachua County",
"282.65234809",
247336,
1,
12,
001
)
2014-06-23 12:04:06.894 KivaJSONDemo[2693:90b] value at 2, ::: (
Florida,
"Alachua County",
"282.65234809",
247336,
2,
12,
001
)
2014-06-23 12:04:06.895 KivaJSONDemo[2693:90b] value at 3, ::: (
Florida,
"Alachua County",
"283.0454668",
247680,
3,
12,
001
)
2014-06-23 12:04:06.895 KivaJSONDemo[2693:90b] value at 4, ::: (
Florida,
"Alachua County",
"285.30018541",
249653,
4,
12,
001
)
.
.
.
.
.
.
.
.
.
在职的:
我让它工作了,但这绝对不是最有效的方法。
NSString *value = @"CTYNAME";
NSUInteger idx = [json[0] indexOfObject:value];
NSString *value2=@"POP";
NSUInteger idx1 = [json[0] indexOfObject:value2];
NSString *value3=@"DENSITY";
NSUInteger idx2 = [json[0] indexOfObject:value2];
if (idx != NSNotFound)
{
for (NSUInteger i = 1; i < [json count]; i=i+6)
{
if (idx < [json[i] count])
{
NSLog(@"County:%@ Population:%@ Density:%@", json[i][idx],json[i][idx1],json[i][idx2]);
[CountyNames addObject:json[i][idx]];
[CountyPopulation addObject:json[i][idx1]];
[CountyDensity addObject:json[i][idx2]];
}
else
{
NSLog(@"Value %@ unavailable in %@", value, json[i]);
}
}
}
else
{
NSLog(@"Value %@ not found.", value);
}