从服务器获取JSON响应

时间:2014-10-28 13:38:57

标签: ios objective-c json

我想使用JSON从服务器获取响应。我在stackoverflow和其他一些网站上搜索了其他答案。但我还没有找到从服务器获取响应的非常简单和最简单的方法。如果有人帮我这样做,它会更好。

1 个答案:

答案 0 :(得分:0)

如果您只是查看我的代码,您可以轻松理解并获得响应。

  //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"]];
     }