如何从Web服务获取JSON数据? iOS目标-c

时间:2013-11-17 20:47:47

标签: php ios objective-c json sqlite

我现在无法找到有用的例子。我的服务器上有一个php脚本,它返回所选数据库表中的所有数据。我试图从我的客户端ios设备获取并解析该json,以便我可以查看其中的内容并将一些数据添加到我的sqlite数据库。我现在正在使用fmdb作为包装器。这是我连接到服务器的代码,我不知道从那里去哪里

  NSURL *url = [NSURL URLWithString:@"http://index.php"];

NSString * post =[NSString stringWithFormat:@"lang=%@",@"English"];

NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setTimeoutInterval:60];

[request setURL:url];
[request setHTTPMethod:@"POST"];

[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];

我的json数据看起来像这样

{"login":[{"userid":"1","password":"test","aclevel":"1"}],"answers":[{"aid":"1","qid":"1","sid":"1","freetext":null,"a":null,"b":null,"c":null,"d":null,"e":null,"f":null,"g":null,"h":null,"i":null,"j":null,"synch":null,"type":null},{"aid":"5","qid":"5","sid":"5","freetext":null,"a":null,"b":null,"c":null,"d":null,"e":null,"f":null,"g":null,"h":null,"i":null,"j":null,"synch":null,"type":null}],"projects":{"pid":"3","name":"apmatt","descr":"tapest","creator":"macurlatt","datetime":null,"synch":null},"questions":[{"qid":"1","pid":"1","sid":"1","question":null,"a":null,"b":null,"c":null,"d":null,"e":null,"f":null,"g":null,"h":null,"i":null,"j":null,"synch":null,"type":null}],"surveys":[{"sid":"2","pid":"2","name":"matt","descr":"test","creator":"matt","datetime":null,"synch":null},{"sid":"3","pid":"3","name":"amatt","descr":"taest","creator":"maatt","datetime":null,"synch":null}]}

1 个答案:

答案 0 :(得分:0)

如果您确定服务器返回如此有效的JSON,那就非常简单了。 iOS提供了NSJSONSerialization类来实现这一目标。以下代码行为您提供了该过程的展望:

__block id data = nil;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue]
                       completionHandler:^(NSURLResponse*       response, NSData* responseData, NSError* err) {
    data = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
}];

如果响应是有效的JSON格式,您可以将数据恢复为“data”变量,该变量可以是基于数据格式的NSArray或NSDictionary,它已经解析过。