NSJSONSerialization - Unable to convert data to string NSJSONSerialization - Unable to convert data to string json json

NSJSONSerialization - Unable to convert data to string


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


What is encoding for the JSON? JSON is supposed to UTF-8 but I have seen lousy APIs where they use ISO-8859-1. NSJSONSerialization only works UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE.