我是解析 JSON 的新手,我正在尝试一个简单的任务,即从预报天气 json 文件中检索 URL。
这里我解析了 json 并且我 NSLog 了数据的每个组成部分的内容:
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&myError];
NSArray *data = [res objectForKey:@"data"];
NSLog(@"data=%@",data);
NSArray *results = [data valueForKey:@"weather"];
NSLog(@"weather=%@",results);
NSArray *results1 = [results valueForKey:@"tempMaxC"];
NSLog(@"tempMaxC=%@",results1);
NSArray *results2 = [results1 valueForKey:@"weatherIconUrl"];
NSLog(@"weatherIconUrl=%@",results2);
问题是当我得到 WeatherIconUrl 时它带有这种格式
"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
我无法在没有引号的情况下获取 url 本身,我尝试使用 nsrange 和 componentsSeparatedByString 但它总是给我这个错误:
[__NSArrayI componentsSeparatedByString:]: unrecognized selector sent to instance
来自服务器的 JSON:
{
"data": {
"current_condition": [
{
"cloudcover": "0",
"humidity": "73",
"observation_time": "12:19 PM",
"precipMM": "0.0",
"pressure": "1021",
"temp_C": "23",
"temp_F": "73",
"visibility": "10",
"weatherCode": "113",
"weatherDesc": [
{
"value": "Sunny"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
}
],
"winddir16Point": "NW",
"winddirDegree": "320",
"windspeedKmph": "17",
"windspeedMiles": "11"
}
],
"request": [
{
"query": "Fanzeres, Portugal",
"type": "City"
}
],
"weather": [
{
"date": "2012-09-12",
"precipMM": "0.0",
"tempMaxC": "28",
"tempMaxF": "83",
"tempMinC": "17",
"tempMinF": "63",
"weatherCode": "113",
"weatherDesc": [
{
"value": "Sunny"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
}
],
"winddir16Point": "NW",
"winddirDegree": "312",
"winddirection": "NW",
"windspeedKmph": "16",
"windspeedMiles": "10"
},
{
"date": "2012-09-13",
"precipMM": "0.0",
"tempMaxC": "33",
"tempMaxF": "91",
"tempMinC": "17",
"tempMinF": "63",
"weatherCode": "113",
"weatherDesc": [
{
"value": "Sunny"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
}
],
"winddir16Point": "N",
"winddirDegree": "8",
"winddirection": "N",
"windspeedKmph": "10",
"windspeedMiles": "6"
}
]
}
}
抱歉我的英语不好,如果我做错了请纠正我,在此先感谢
最佳答案
从 @"weatherIconUrl"获取数组时使用 objectForKey 而不是 valueForKey 然后将字符串获取到 NSString 例如
NSString *weatherIconUrlString = [results2 objectAtIndex:0]
要检查这是一个有效的 url,请使用 NSURLConnection 的 canHandleRequest 方法,例如
NSURL *url = [NSURL URLWithString:weatherIconUrlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url
BOOL canGo = [NSURLConnection canHandleRequest:request];
关于iphone - 如何用字符串分隔的组件进行json解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12385219/