我正在使用Bing Search API并且能够成功解析xml但不能成功解析JSON.Below是解析xml和JSON的代码,当我在nslog输出JSON时显示“null”我不知道如何从这里开始。
-(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 (不成功)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
// convert to JSON
NSLog(@"Finished loading: Received %d bytes of data",[self.responseData length]);
NSXMLParser *parser = [[NSXMLParser alloc] initWithData: self.responseData];
[parser setDelegate: self];
[parser parse];
NSLog(@"XMl == %@",parser);
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&myError];
NSLog(@"json data = %@",res);//getting null
}
使用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"
}
]
}
}
}
答案 0 :(得分:0)
从你的帖子:
NSXMLParser *parser = [[NSXMLParser alloc] initWithData: self.responseData];
.
.
.
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&myError];
看起来您正在尝试使用与XML和JSON相同的数据。你不能这样做。从服务器返回的数据是一种形式或另一种形式。它不会两者兼有。