json返回格式

时间:2013-03-28 05:30:30

标签: iphone ios json

Api地址: http://suggest.taobao.com/sug?area=etao&code=utf-8&callback=KISSY.Suggest.callback&q=iphone

返回:

KISSY.Suggest.callback({"result": [["iphone4s", "9809"], ["iphone5", "13312"], ["iphone4 手机", "69494400"], ["iphone5 港行", "14267"], ["iphone5三网", "2271160"], ["iphone4手机壳", "6199679"], ["iphone 5手机壳", "2527284"], ["iphone 5 保护壳", "5727586"], ["iphone 4贴膜", "147271"], ["iphone5壳", "2628540"]]})


NSURL * url = [NSURL URLWithString:@"http://suggest.taobao.com/sug?area=etao&code=utf-8&callback=KISSY.Suggest.callback&q=iphone"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

NSHTTPURLResponse* urlResponse = nil;

NSError * error = nil;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];

NSData *date = [NSData alloc]init

SBJsonParser *jsonParser = [[SBJsonParser alloc] init];


// NSMutableArray *array=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
    NSMutableArray *array = [jsonParser objectWithData:responseData];

    NSLog(@"%@",array);

此数组为null。我不知道原因。

3 个答案:

答案 0 :(得分:1)

当我引用你的请求URL时,它有回调函数,如果你保留它,它将不会返回json作为响应,所以从你的URL中删除“& callback = KISSY.Suggest.callback”

// Make sure you have include SBJSON files in your Project, as well you have imported header in your View Controller
#import "JSON.h"

// your request URL
NSURL * url = [NSURL URLWithString:@"http://suggest.taobao.com/sug?area=etao&code=utf-8&q=iphone"];

// URL Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

NSHTTPURLResponse* urlResponse = nil;

NSError * error = nil;

// initiate Request to get Data
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];

// Encode your Response
NSString *content = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSUTF8StringEncoding];

// Now read a Dictionary from it using SBJSON Parser
NSDictionary *responseDict = [content JSONValue];

NSLog(@"Response [%@]",responseDict);

答案 1 :(得分:0)

我不熟悉SBJsonParser,但返回的字符串的格式看起来像JSONP,而不是JSON。我想,简单地清理包装器调用会让你得到你想要的东西。

另请注意,您的回复的“根”是字典,而不是数组。

{"result": [[...

表示代码可能如下所示:

NSDictionary *response = //... decode
NSArray *results = [response objectForKey:@"result"];

答案 2 :(得分:0)