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

标签 ios objective-c json web-services cocoa-touch

我在使用 NSJSONSerialization 从 Met Office Datapoint API 读取 JSON 时遇到问题。

出现以下错误

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 本身似乎是有效的,而且我希望它也来自英国气象局等大型组织。

NSJSONSerialization 不应该对诸如 'ó' 这样的字符正常工作吗?

如果不是,我该如何改变编码类型来处理这个问题?

提前致谢

最佳答案

英国气象局数据点以 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]);
}

关于ios - NSJSONSerialization - 无法将数据转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14485868/

相关文章:

javascript - 从 javascript 数组中删除一个元素

iphone - 如何在多 TableView 中过滤数据

objective-c - ualarm() 的 iOS( Objective-C )版本

android - 如何创建具有动态 key 的 pojoclass

iphone - 将 NSString 中的 ""字符替换为 "\"(以创建 Unix 路径)

iphone - 如何获得 iPhone OS 3.1 低沉的键盘声音?

ios - 将 JSON 解析为字典,判断真假

ios - AudioQueueStart 发布消息以终止 mediaserverd

ios - UIImagePickerController 编辑的图像在 iPad 中检索错误的图像

ios - Facebook Graph API GET 请求 - 应包含 "fields"参数(Swift,Facebook SDK v4.5.1)