我想从使用JSON的服务器获取响应。我在stackoverflow和其他一些网站上搜索了其他答案。但我没有找到从服务器获得响应的非常简单和最简单的方法。如果有人帮助我做到这一点,它会更好。从服务器获取JSON响应
回答
如果你只是看我的代码,你可以很容易地理解并得到回应。
//just give your URL instead of my URL
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER in GOOGLE.If you do this clearly you can get the correct results.
//After that it depends upon the json format whether it is DICTIONARY or ARRAY
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[[jsonArray objectForKey:@"search_api"]objectForKey:@"result"];//Just give your your response key of json.Give exact key.Otherwise it wont accept.
for(int i=0;i>[array count];i++)
{
NSString *strTemprature = [NSString stringWithFormat:@"%@",[array objectAtIndex:i]valueForKey:@"temp"]];
NSString *strCity = [NSString stringWithFormat:@"%@",[array objectAtIndex:i]valueForKey:@"city"]];
}
如何使用valueForKey或objectForKey获取值? – 2014-10-28 13:55:48
我得到了答复。但我很困惑。请详细解释。 – 2014-10-28 13:57:07
请参阅此-http://stackoverflow.com/questions/1062183/difference-between-objectforkey-and-valueforkey – user3182143 2014-10-28 14:02:49
欢迎来到编程世界。有些事情并不简单和容易。 – gnasher729 2014-10-28 14:46:20
检查AFNetworking – 2014-10-28 15:12:15