我已经阅读了文档,教程和其他Stack Q&A,并且对如何使用JSON
而不是NSUTF8StringEncoding
使NSJSONSerialization
出现感到困惑,这是我需要将数据提取到NSDictionary
或NSArray
。我认为从我的网址返回的NSData
格式存在问题吗?
编辑这是错误:错误域= NSCocoaErrorDomain代码= 3840“该操作无法完成。(可可错误3840。)”(结束时是垃圾。)UserInfo = 0x8aabc30
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.sampleURL.com"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:15.0];
NSMutableData* responseData = [NSMutableData dataWithCapacity: 0];
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
//this works, and have NSLog below
responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"string %@", responseString);
[responseData appendData:data];
responseData = [[NSMutableData alloc] initWithData:data];
//this is null in NSLog
NSError * error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&error];
NSLog(@"jsonDict dict %@",jsonDict);
}
调试控制台:
2014-03-11 07:41:58.233 WBPC[7845:a0b] string {"id":"a1","session":"General","name":"Exhibitor Setup Begins","startTime":"0900","details":"9am Exhibitor Hall","png":"image","speaker1":"Johnson","speaker2":"Nelson","speaker3":""}{"id":"b1","session":"General","name":"Conference Registration","startTime":"1000","details":"10am Noon Upper Level Lobby","png":"image","speaker1":"Jackson","speaker2":"","speaker3":""}
2014-03-11 07:41:58.236 WBPC[7845:a0b] jsonDict (null)
最佳答案
您的JSON格式不正确。您告诉我们这是(为清晰起见添加了空格和换行符):
{
"id": "a1",
"session": "General",
"name": "Exhibitor Setup Begins",
"startTime": "0900",
"details": "9am Exhibitor Hall",
"png": "image",
"speaker1": "Johnson",
"speaker2": "Nelson",
"speaker3": ""
}{
"id": "b1",
"session": "General",
"name": "Conference Registration",
"startTime": "1000",
"details": "10am Noon Upper Level Lobby",
"png": "image",
"speaker1": "Jackson",
"speaker2": "",
"speaker3": ""
}
缺少两个字典条目之间的逗号,并且缺少应包装JSON的
[
和]
。如果确实是字典条目的数组,则应为:[
{
"id": "a1",
"session": "General",
"name": "Exhibitor Setup Begins",
"startTime": "0900",
"details": "9am Exhibitor Hall",
"png": "image",
"speaker1": "Johnson",
"speaker2": "Nelson",
"speaker3": ""
},
{
"id": "b1",
"session": "General",
"name": "Conference Registration",
"startTime": "1000",
"details": "10am Noon Upper Level Lobby",
"png": "image",
"speaker1": "Jackson",
"speaker2": "",
"speaker3": ""
}
]
如果要检查JSON,可以访问http://jsonlint.com。另外,如果您检查了
error
返回的JSONObjectWithData
对象,它将为您指明正确的方向。您应该查看如何生成此JSON。看起来它必须是手动生成的。例如,如果是从PHP页面生成的,则应使用
json_encode
,而不是手动生成JSON。顺便说一句,您正在尝试将结果解析为
didReceiveData
。在connectionDidFinishLoading
之前,您不应该尝试解析。您的didReceiveData
应该仅将data
附加到NSMutableData
对象。解析应该推迟到connectionDidFinishLoading
为止。