【发布时间】:2015-05-02 04:35:09
【问题描述】:
我有一个如下所示的 JSON 文件:
test.Data({
"field": "try",
"date": "20150501",
"data": [
"<sample1 code_date=\"2015050110\" type=\"play\"><sample2 name=\"foo\" place=\"bar\">"]
});
我尝试使用以下方法阅读它:
NSString *urlAsString = [NSString stringWithFormat:@"localhost"];
NSURL *url = [[NSURL alloc] initWithString:urlAsString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if ([data length] > 0 && connectionError == nil)
_textLabel.stringValue = @"Good";
else if ([data length] == 0 && connectionError == nil)
_textLabel.stringValue = @"Nothing to load";
else if (connectionError != nil)
_textLabel.stringValue = connectionError.userInfo[@"NSLocalizedDescription"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error: &e];
if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(@"Item: %@", item);
}
}
});
但我收到以下错误:
解析 JSON 时出错:Error Domain=NSCocoaErrorDomain Code=3840“无法读取数据,因为它的格式不正确。” (字符 0 周围的值无效。) UserInfo=0x61800006e880 {NSDebugDescription=字符 0 周围的值无效。}
知道如何使用标准 JSON 解析器将这种 JSON 格式读入 Xcode 吗?
【问题讨论】:
-
文件内容不是有效的 JSON,看起来更像是一个方法调用。
-
更新服务器以返回有效的 JSON。
-
当
NSURLConnection请求完成处理程序已经在后台线程上运行时,为什么还要使用dispatch_async在另一个后台线程上运行该代码? -
我是这种方法的新手,我仍在阅读它。这部分代码来自一个教程。我想没有必要吧?
标签: ios objective-c json parsing