gpt4 book ai didi

iphone - NSURL 连接和 json

转载 作者:行者123 更新时间:2023-12-01 17:21:19 25 4
gpt4 key购买 nike

我知道这是一个愚蠢的问题,但我不知道该怎么做。从这个链接the requested link可以使用 NSURLconnection 返回 json 数据吗?我希望有人检查此链接并告诉我这是否可能,因为我是这方面的新手。

编辑:

我试过 NSJSON序列化

- (void)viewDidLoad
{
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.goalzz.com/main.aspx?region=-1&area=6&update=true"]];
connectionData = [[NSURLConnection alloc]initWithRequest:req delegate:self];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
Data = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[Data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *jsonParsingError = nil;
id object = [NSJSONSerialization JSONObjectWithData:Data options:0 error:&jsonParsingError];

if (jsonParsingError) {
NSLog(@"JSON ERROR: %@", [jsonParsingError localizedDescription]);
} else {
NSLog(@"OBJECT: %@", [object class]);
}
}

我在控制台中收到此错误消息:

JSON 错误:操作无法完成。 ( cocoa 错误 3840。)

最佳答案

正如上面的评论所暗示的,该链接不返回 JSON。但是,假设您确实有这样的链接,您可以使用 NSJSONSerialization 类将 JSON 数据解析为 Objective-C 类:

http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40010946

将此与 NSURLConnection 结合起来,您就可以按照您的要求进行操作。下面是实现 NSURLConnection 的演练:

http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE

这是您需要的概述。显然这不是工作代码:

- (void)downloadJSONFromURL {
NSURLRequest *request = ....
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
// ...
}

NSMutableData *urlData;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
urlData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[urlData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *jsonParsingError = nil;
id object = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];

if (jsonParsingError) {
DLog(@"JSON ERROR: %@", [jsonParsingError localizedDescription]);
} else {
DLog(@"OBJECT: %@", [object class]);
}
}

关于iphone - NSURL 连接和 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11319572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com