Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

ios - NSJSONSerialization - Unable to convert data to string

I'm having a problem with NSJSONSerialization reading JSON from the Met Office Datapoint API.

I get the following error

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

I have checked and think this is the offending line according to the character position

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

The JSON itself appears to be valid according to a couple of Validators I tried, and I would expect it too be from a large organisation such as Met Office.

Shouldn't NSJSONSerialization work fine with characters such as 'ó'?

If not how do I go about changing the encoding type to deal with this?

Many Thanks in Advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Met Office Datapoint sends back data in ISO-8859-1 which isn't one of the supported data format for NSJSONSerialization.

To make it work create a string from the URL content at first with NSISOLatin1StringEncoding and then create the NSData you want to use in the NSJSONSerialization with a NSUTF8 encoding.

The following works to create the corresponding json object

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]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...