gpt4 book ai didi

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

转载 作者:技术小花猫 更新时间:2023-10-29 11:11:38 26 4
gpt4 key购买 nike

我在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com