9

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 は「ó」などの文字で正常に動作するはずではありませんか?

そうでない場合、これに対処するためにエンコーディングタイプを変更するにはどうすればよいですか?

よろしくお願いします

4

2 に答える 2

21

Met Office Datapoint は、NSJSONSerialization でサポートされているデータ形式の 1 つではない ISO-8859-1 でデータを送り返します。

これを機能させるには、最初に 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]);
}
于 2013-01-23T18:31:41.927 に答える
4

JSON のエンコーディングとは何ですか? JSON は UTF-8 を想定していますが、ISO-8859-1 を使用するお粗末な API を見てきました。NSJSONSerialization は、UTF-8、UTF-16LE、UTF-16BE、UTF-32LE、UTF-32BE のみで機能します。

于 2013-01-23T17:47:23.483 に答える