iOS 5 JSONparsingCocoa错误3840的结果
我很难在iOS 5上parsing下面的JSONstring。
{"States": [{"Name": "Arizona","Cities": [{"Name": "Phoenix"}]},{"Name": "California","Cities": [{"Name": "Orange County"},{"Name": "Riverside"},{"Name": "San Diego"},{"Name": "San Francisco"}]},{"Name": "Nevada","Cities": [{"Name": "Las Vegas"}]}]}
这是我的代码:
- (void) parseJson { NSError *jsonError = nil; NSData *jsonData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Locations-JSON" ofType:@"rtf"]]; if (jsonData) { NSDictionary *jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&jsonError]; if (jsonError) { NSLog(@"JSON Error: %@", [jsonError localizedDescription]); return; } NSLog(@"%@", jsonObjects); } }
我不断收到这个错误:
JSON Error: The operation couldn't be completed. (Cocoa error 3840.)
我会很感激这方面的一些帮助,因为我显然无法解决这个问题。
有一件事让我觉得不正确的是:
[[NSBundle mainBundle] pathForResource:@"Locations-JSON" ofType:@"rtf"]
你的数据是一个RTF文件? 它应该是一个txt
文件(或任何其他types的纯文本文件)。 RTF文件通常包含文本格式数据,如下所示:
{\rtf1\ansi\ansicpg1252\cocoartf1138\cocoasubrtf470 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \margl1440\margr1440\vieww10800\viewh8400\viewkind0 \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural \f0\fs24 \cf0 \{"States": [\{"Name": "Arizona","Cities": [\{"Name": "Phoenix"\}]\},\{"Name": "California","Cities": [\{"Name": "Orange County"\},\{"Name": "Riverside"\},\{"Name": "San Diego"\},\{"Name": "San Francisco"\}]\},\{"Name": "Nevada","Cities": [\{"Name": "Las Vegas"\}]\}]\}}
当我读取数据并尝试将其parsing为JSON时,出现您看到的3840错误。 那个错误的描述说:
数据无法读取,因为它已损坏。 (在字符2周围的对象中没有string值)
所以对我来说,看起来实际上并没有JSON。 你有RTF数据。
我遇到了类似的问题。 当我从服务器下载JSON数据时,我的JSONparsing器间歇性地工作。 你从这个函数得到了你的JSON数据吗?
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
从这个函数返回的NSData可能是部分数据。 你需要appendData到types为NSMutableData的实例variables。 然后你在另一个函数中处理你的JSON,如下所示:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
阅读这篇文章的细节。 这个对我有用
我能够通过将NSData
对象转换为NSString
来解决我的JSON 3840错误:
NSError *error; NSObject *object = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; if (object == nil) { NSString *serverResponse = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding]; NSLog(@"\n\nError:\n%@\n\nServer Response:\n%@\n\nCrash:", error.description, serverResponse); [NSException raise:@"Invalid Data" format:@"Unable to process web server response."]; }
如果你因为JSON而不是因为RTF而来到这里,请查看这个答案: IOS JSON反序列化失败 – STIG / NSJSONSerializer