2014-01-23 139 views
-1

我试图将NSData从外部JSON文件转换为NSArray以将其显示在UITableView对象中。将NSData转换为NSArray返回null/error

返回null:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/json.php"]]; 
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
    NSArray *responseArray = [NSJSONSerialization JSONObjectWithData:response options:0 error:NULL]; 
    NSLog(@"%@", responseArray); 

这将返回Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSKeyedUnarchiver initForReadingWithData:]: incomprehensible archive

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/json.php"]]; 
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
    NSLog(@"%@", response); 
    NSArray *responseArray = [NSKeyedUnarchiver unarchiveObjectWithData:response]; 
    NSLog(@"%@", responseArray); 

我的JSON格式是这样的:

["The Savoy", "London"]["The Ritz", "London"]["Hilton", "New York"]["Marriott", "San Francisco"] 

我有一种感觉这是我的JSON格式造成问题的原因,但我不确定...

编辑

非常感谢您的回复。我的JSON和错误处理现在看起来是这样,但我收到同样的空响应:

[{"name":"The Savoy", "city":"London}] 
[{"name":"The Ritz", "city":"London}] 
[{"name":"Hilton", "city":"New York}] 
[{"name":"Marriott", "city":"San Francisco}] 

的Objective-C:

NSError *error = nil; 
NSArray *responseArray = [NSJSONSerialization JSONObjectWithData:response options:0 error:&error]; 
NSLog(@"%@", responseArray); 
+2

这不是有效的JSON 。如果你想要一个数组数组,你需要在整个事物中添加一组方括号。 – rmaddy

+0

如果我只有一个具有这些值的数组,它会有效吗?这就是我最初尝试过的,并没有奏效。 – Sebastian

+1

顺便说一句 - 你应该在调用'JSONObjectWithData'时使用error参数,以便找出实际问题。 – rmaddy

回答

3

你JSON是错误的 - 而不是

["The Savoy", "London"]["The Ritz", "London"]["Hilton", "New York"]["Marriott", "San Francisco"] 

使用

[["The Savoy", "London"],["The Ritz", "London"],["Hilton", "New York"],["Marriott", "San Francisco"]] 
+0

更好''[[“hotel_name”:“萨沃伊”,“hotel_location”:“伦敦”],...]'如果你可以更换服务器。 – vikingosegundo