我能够从天气图api中检索数据,但是我无法弄清楚如何精确地解析数据。我只能在它的某个部分做到这一点。
这是JSON数据:
{
base = "cmc stations";
clouds = {
all = 56;
};
cod = 200;
coord = {
lat = "29.66";
lon = "-82.3";
};
dt = 1403641995;
id = 4156404;
main = {
humidity = 74;
pressure = 1018;
temp = "304.08";
"temp_max" = "306.48";
"temp_min" = "302.15";
};
name = Gainesville;
rain = {
3h = 0;
};
sys = {
country = US;
message = "0.2087";
sunrise = 1403605821;
sunset = 1403656392;
};
weather = (
{
description = "broken clouds";
icon = 04d;
id = 803;
main = Clouds;
}
);
wind = {
deg = 153;
gust = "1.54";
speed = "0.51";
};
}
现在我只能得到它的一部分: base =“cmc stations”
像这样:- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSLog(@"values %@",json);
NSLog(@"Checking values ------------ %@",[json objectForKey:@"cloud"]);
}
但是当我尝试为其他领域做同样的事情时 云 坐标 主
我做不到。我得到一个空值。
我猜我需要一个额外的NSDictionary或NSArray,但只是不确定如何去做。有人可以告诉我该怎么做?我主要是想从主要块中获取数据:
humidity
temp
temp_max
temp_min
rain
sunrise
sunset
我想我找到了一个解决方案:
以下是我获取数据的方式:
NSString* base = [json objectForKey:@"base"];
NSLog(@"Value of first base variable: %@",base);
// NSArray* base = [json objectAtIndex:0];
NSArray *clouds = [json objectForKey:@"clouds"];
NSLog(@"Value of first clouds‹ variable: %@",clouds);
NSArray *coord = [json objectForKey:@"coord"];
NSLog(@"Value of first coord variable: %@",coord);
NSDictionary *main = [json objectForKey:@"main"];
NSLog(@"Value of first coord variable: %@",main);
NSArray* humidity = [main objectForKey:@"humidity"];
NSLog(@"humidity levels found manually : %@",humidity);
NSArray* temp_max = [main objectForKey:@"temp_max"];
NSLog(@"max temp levels found manually : %@",temp_max);
答案 0 :(得分:0)
问题是这些值中的大多数是字典,而不是数组。当您看到{
}
和冒号(:
)时,通常会指示键值对字典的存在,即使其中一些可能只有一个这样的一对使它看起来像一个数组或一个独立的对象。
例如获取clouds
:
NSDictionary *clouds = [json objectForKey:@"clouds"];
NSNumber *allClouds = [clouds objectForKey:@"all"];
NSLog(@"Value of first clouds‹ variable: %@",allClouds);
获取coord
:
NSDictionary *coords = [json objectForKey:@"coord"];
NSNumber *lon = [coords objectForKey:@"lon"];
NSNumber *lat = [coords objectForKey:@"lat"];
NSLog(@"Value of lon is: %@",lon);