将NSData转换为NSArray会返回null / error

时间:2014-01-23 22:43:30

标签: ios objective-c json uitableview

我正在尝试将NSData从外部JSON文件转换为NSArray,以便在UITableView对象中显示它。

返回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}]

目标-C:

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

1 个答案:

答案 0 :(得分: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"]]