小编典典

NSJSONSerialization-无法将数据转换为字符串

json

我从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"}

根据我尝试过的多个验证器,JSON本身似乎是有效的,并且我希望它也来自大型组织(如Met Office)。

NSJSONSerialization是否不能与’ó’之类的字符配合使用?

如果不是,我该如何更改编码类型以解决此问题?

提前谢谢了


阅读 249

收藏
2020-07-27

共1个答案

小编典典

大都会办公室数据点以ISO-8859-1的形式发回数据,这不是NSJSONSerialization支持的数据格式之一。

为了使其工作,首先使用NSISOLatin1StringEncoding从URL内容创建一个字符串,然后使用NSUTF8编码创建要在NSJSONSerialization中使用的NSData。

下面的工作来创建相应的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]);
}
2020-07-27