Ios 使用NSURLConnection解析JSON
我正在使用Bing搜索API,能够成功解析xml而不是JSON。下面是解析xml和JSON的代码,当我记录JSON的输出时,它显示“null”,我不知道如何从这里开始Ios 使用NSURLConnection解析JSON,ios,xml,json,nsurlconnection,Ios,Xml,Json,Nsurlconnection,我正在使用Bing搜索API,能够成功解析xml而不是JSON。下面是解析xml和JSON的代码,当我记录JSON的输出时,它显示“null”,我不知道如何从这里开始 -(void)searchBing:(NSString *)text{ //NSString *query1 = @"San Francisco Baseball"; NSString *query = [NSString stringWithFormat: @"'%@'",text]; //NSStr
-(void)searchBing:(NSString *)text{
//NSString *query1 = @"San Francisco Baseball";
NSString *query = [NSString stringWithFormat: @"'%@'",text];
//NSString *query = query1;
NSString *format = @"atom";
NSString *market = @"'en-us'";
//NSInteger top = 2;
NSMutableString *fullURL = [NSMutableString stringWithCapacity:256];
[fullURL appendString:URL];
[fullURL appendFormat:@"Web?$format=%@", format];
[fullURL appendFormat:@"&Query=%@",
[query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[fullURL appendFormat:@"&Market=%@",
[market stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// [fullURL appendFormat:@"&$top=%d", top];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:
[self getRequest:fullURL] delegate:self];
if (connection)
{
NSLog(@"Connection established");
}
else
{
NSLog(@"Connection failed");
}
}
下面是我解析xml(成功)和JSON(不成功)的地方
我使用Base_64编码,对所有观众来说,查询没有错,因为通过xml解析器获得正确的信息。但我希望得到JSON格式的响应
结构样品
{
"SearchResponse":{
"Version":"2.2",
"Query":{
"SearchTerms":"testign"
},
"Spell":{
"Total":1,
"Results":[
{
"Value":"testing"
}
]
},
"Web":{
"Total":5100,
"Offset":0,
"Results":[
{
"Title":"Testign part 2 - Tiernan OTooles Programming Blog",
"Description":"If this works, it means nothing really, but i have managed to build a .TEXT blog posting app. could be handy if i move my main blog to .TEXT, which i am thinking about..",
"Url":"http:\/\/weblogs.asp.net\/tiernanotoole\/archive\/2004\/09\/24\/233830.aspx",
"DisplayUrl":"http:\/\/weblogs.asp.net\/tiernanotoole\/archive\/2004\/09\/24\/233830.aspx",
"DateTime":"2008-10-21T05:08:05Z"
}
]
}
}
}
从您的帖子:
NSXMLParser *parser = [[NSXMLParser alloc] initWithData: self.responseData];
.
.
.
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&myError];
看起来您正在尝试使用与XML和JSON相同的数据。你不能那样做。从服务器返回的数据是一种形式或另一种形式。不会两者都是。你也检查数据是否为空?相同的数据通过xml可见,但通过jsonit不可见。这很奇怪,因为如果数据良好,你必须确保有json解析,你能给我提供json的链接吗?恐怕不可能,因为你需要api密钥[必应的]但我的问题是解析是否正确?是的,但您可以为我检查是否返回json并编写scructure?现在我只有NSString*json=[[NSString alloc]initWithData:self.responseData encoding:NSUTF8StringEncoding];n错误*myError=nil;NSDictionary*res=[NSJSONSerialization JSONObjectWithData:self.responseData选项:编织错误:&myError];NSLog(@“json数据=%@”,json);NSLog(@“\n\n\n\n\n\n数据=%@”,res);很抱歉,我不能像你那样以更好的方式呈现代码。
NSXMLParser *parser = [[NSXMLParser alloc] initWithData: self.responseData];
.
.
.
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&myError];