我可以从API检索整个JSON响应并将其存储在NSArray中。如何从JSON响应中获取字段值
然后我遍历整个响应并将每个结果组存储在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 *[email protected]"POP";
NSUInteger idx1 = [json[0] indexOfObject:value2];
NSString *[email protected]"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);
}
盖伊是正确的,JSON数据可以拿出作为数组和字典,这取决于如何将数据最初时编码的任意组合。如果您在读取json后读取数据,则可以了解您是否拥有数组数组或字典数组。 (这将有键:值表达式) –