我有一个很难解析在iOS 5以下JSON字符串。
{"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
文件(或任何其他类型的纯文本文件)。 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"\}]\}]\}}
当我读到,在作为数据并尝试分析它作为JSON,我得到了3840的错误你看到。 该错误的描述说:
这些数据无法读取,因为它已被损坏。 (为值对象周围文字2.无串键)
那么它是什么样子给我的是,你实际上并不JSON。 你有RTF数据。
我已经打了一个类似的问题。 当我从服务器上下载JSON数据的json解析器间歇工作。 你从这个功能让你的JSON数据?
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
NSData的从这个函数返回的可能是部分数据。 您需要appendData与类型的实例变量:NSMutableData。 然后,你处理你的JSON在另一个函数如下:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
看完这篇文章的详细信息。 这个对我有用
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
我能够通过转换来解决我的JSON 3840错误NSData
对象到NSString
:
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."];
}
如果你到了,因为而不是RTF,因为JSON的在这里,请看看这个答案: IOS JSON反序列化失败- STIG / NSJSONSerializer