NSJSONSerialization – 无法将数据转换为string

我遇到了从Met Office Datapoint API读取JSON的NSJSONSerialization问题。

我得到以下错误

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn't be completed. (Cocoa error 3840.)" (Unable to convert data to string around character 58208. 

我已经检查并认为这是根据字符位置的违规行

 {"id":"353556","latitude":"57.1893","longitude":"-5.0929","name":"Sóil Chaorainn"} 

根据我尝试过的几个validation器,JSON本身似乎是有效的,我也希望它也来自Met Office这样的大型组织。

NSJSONSerialization不应该与'ó'这样的字符一起工作吗?

如果不是我怎么去改变编码types来处理这个?

提前谢谢了

Met Office Datapoint发送的ISO-8859-1中的数据不是NSJSONSerialization支持的数据格式之一。

为了使它工作,首先使用NSISOLatin1StringEncoding从URL内容创build一个string,然后用NSUTF8编码创buildNSJSONSerialization中要使用的NSData。

下面的工作来创build相应的json对象

 NSError *error; NSString *string = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json/sitelist?key=<YOUR_API_KEY"] encoding:NSISOLatin1StringEncoding error:&error]; NSData *metOfficeData = [string dataUsingEncoding:NSUTF8StringEncoding]; id jsonObject = [NSJSONSerialization JSONObjectWithData:metOfficeData options:kNilOptions error:&error]; if (error) { //Error handling } else { //use your json object NSDictionary *locations = [jsonObject objectForKey:@"Locations"]; NSArray *location = [locations objectForKey:@"Location"]; NSLog(@"Received %d locations from the DataPoint", [location count]); } 

什么是JSON的编码? JSON应该是UTF-8,但我已经看到糟糕的API,他们使用ISO-8859-1。 NSJSONSerialization只能使用UTF-8,UTF-16LE,UTF-16BE,UTF-32LE,UTF-32BE。