如何通过Objective C从网页获取Json字符串

时间:2012-03-29 05:32:37

标签: objective-c json

我将值发布到文本字段并返回JSON字符串,如何发布值/接收JSON字符串。

这是我的代码:

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.donxebuyt.com/"]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:txtFrom.text forKey:@"id_locA"];
[request setRequestMethod:@"POST"];

[request setCompletionBlock:^{
    NSString *responseString = [request responseString];
    NSLog(@"Response: %@", responseString);
}];
[request setFailedBlock:^{
    NSError *error = [request error];
    NSLog(@"Error: %@", error.localizedDescription);
}];

[request startAsynchronous];

2 个答案:

答案 0 :(得分:9)

NSData *data=[NSData dataWithContentsOfURL:url];
NSError *error=nil;
NSDictionary *response=[NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error:&error]; 
NSString* sth=[response objectForKey: @"some_your_key"];

sth是一个新变量,并在上面发布时将其发布

答案 1 :(得分:1)

iOS有一个内置的json序列化框架(只需在项目中包含JSON.framework)或者有一些开源框架,如JSONKit:https://github.com/johnezang/JSONKit