ios 目标c从url请求解析json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20077328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
objective c parse json from url request
提问by Wouter Willems
I am trying to parse a json string requested from an api located at: http://www.physics.leidenuniv.nl/json/news.php
我正在尝试解析从位于以下位置的 api 请求的 json 字符串:http: //www.physics.leidenuniv.nl/json/news.php
However, i am having trouble parsing this json.
I get the following error:
Unexpected end of file during string parse
但是,我在解析这个 json 时遇到了问题。我收到以下错误:
Unexpected end of file during string parse
I have looked for hours, but I can not find an answer to this problem.
我已经找了几个小时,但我找不到这个问题的答案。
My code snippet:
我的代码片段:
In my viewDidLoad:
在我看来DidLoad:
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:@"http://www.physics.leidenuniv.nl/json/news.php"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
The delegate:
代表:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableData *responseData = [[NSMutableData alloc] init];
[responseData appendData:data];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSError *e = nil;
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e];
}
Anybody know an answer to this problem so i can parse the json data?
有人知道这个问题的答案,所以我可以解析 json 数据吗?
采纳答案by Bhumeshwer katre
Do this way:
这样做:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSError *e = nil;
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e];
}
回答by Peter Foti
I would recommend doing it this way:
我建议这样做:
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.physics.leidenuniv.nl/json/news.php"]];
__block NSDictionary *json;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
json = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSLog(@"Async JSON: %@", json);
}];
Or if for whatever reason (not recommended) you want to run a synchronous request you could do:
或者,如果出于某种原因(不推荐)您想要运行同步请求,您可以执行以下操作:
NSData *theData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:nil];
NSDictionary *newJSON = [NSJSONSerialization JSONObjectWithData:theData
options:0
error:nil];
NSLog(@"Sync JSON: %@", newJSON);
回答by Gangani Roshan
Simple Way to store json-url data in dictionary.
在字典中存储 json-url 数据的简单方法。
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://query.yahooapis.com/v1/public/yql?q=select+%2A+from+weather.forecast+where+woeid%3D1100661&format=json"]];
NSError *error=nil;
id response=[NSJSONSerialization JSONObjectWithData:data options:
NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];
if (error) {
NSLog(@"%@",[error localizedDescription]);
} else {
_query = [response objectForKey:@"query"];
NSLog(@"%@",_query);
You can try this, so easy.
你可以试试这个,很简单。
回答by Andal Priyadharshni V
//call this method
-(void)syncWebByGETMethod
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:@"http://www.yoursite.com"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
{
if (data)
{
id myJSON;
@try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
@catch (NSException *exception) {
}
@finally {
}
jsonArray = (NSArray *)myJSON;
NSLog(@"mmm %@",jsonArray);
}
}];
}
回答by Bala Murugan
-(void)getWebServic{
NSURL *url = [NSURL URLWithString:@"----URL----"];
// 2
NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession]
dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSDictionary *jsonObject=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
[self loadDataFromDictionary:(NSArray*)jsonObject];
NSLog(@"data: %@",jsonObject);
}];
// 3
[downloadTask resume]; }
回答by Macondo2Seattle
One solution is to use NSURLConnection sendSynchronousRequest:returningResponse:error:
(docs). In the completion handler you'll have ALL the response data, not just the partial data you get in the delegate's connection:didReceiveData:
method.
一种解决方案是使用NSURLConnection sendSynchronousRequest:returningResponse:error:
( docs)。在完成处理程序中,您将拥有所有响应数据,而不仅仅是您在委托connection:didReceiveData:
方法中获得的部分数据。
If you want to keep using the delegate, you'll need to follow the advice in the Apple docs:
如果您想继续使用委托,则需要遵循Apple 文档中的建议:
The delegate should concatenate the contents of each data object delivered to build up the complete data for a URL load.
委托应连接交付的每个数据对象的内容,以构建用于 URL 加载的完整数据。
回答by Vvk
Volunteermatch API Objective C
i am using one common methods for AFNetworking WS Calling. Uses:
我正在使用 AFNetworking WS 调用的一种常用方法。用途:
Call WS:
致电 WS:
NSDictionary* param = @{
@"action":@"helloWorld",
@"query":@"{\"name\":\"john\"}"
};
[self requestWithUrlString:@"URL" parmeters:paramDictionary success:^(NSDictionary *response) {
//code For Success
} failure:^(NSError *error) {
// code for WS Responce failure
}];
Add Two Methods: this two methods are common,u can use these common method in whole project useing NSObject class. also add // define error code like...
添加两个方法:这两个方法是通用的,你可以使用 NSObject 类在整个项目中使用这些通用方法。还添加 // 定义错误代码,如...
define kDefaultErrorCode 12345
定义 kDefaultErrorCode 12345
- (void)requestWithUrlString:(NSString *)stUrl parmeters:(NSDictionary *)parameters success:(void (^)(NSDictionary *response))success failure:(void (^)(NSError *error))failure {
[self requestWithUrl:stUrl parmeters:parameters success:^(NSDictionary *response) {
if([[response objectForKey:@"success"] boolValue]) {
if(success) {
success(response);
}
}
else {
NSError *error = [NSError errorWithDomain:@"Error" code:kDefaultErrorCode userInfo:@{NSLocalizedDescriptionKey:[response objectForKey:@"message"]}];
if(failure) {
failure(error);
}
}
} failure:^(NSError *error) {
if(failure) {
failure(error);
}
}];}
and // Set Headers in Below Method (if required otherwise remove)
和 // 在下面的方法中设置标题(如果需要,否则删除)
- (void)requestWithUrl:(NSString *)stUrl parmeters:(NSDictionary *)parameters success:(void (^)(NSDictionary *response))success failure:(void (^)(NSError *))failure {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
[manager.requestSerializer setValue:@"WWSE profile=\"UsernameToken\"" forHTTPHeaderField:@"Authorization"];
[manager GET:stUrl parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
if([responseObject isKindOfClass:[NSDictionary class]]) {
if(success) {
success(responseObject);
}
}
else {
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
if(success) {
success(response);
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
if(failure) {
failure(error);
}
}];}
For any issues and more Detail please visit..AFNetworking
对于任何问题和更多详细信息,请访问..AFNetworking