Reputation: 649
I'm trying to deserialize JSON coming from the server using NSJsonSerialization. The server returns a png image converted to a string. Here is my code:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSError *deserializationError;
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&deserializationError];
if (deserializationError) {
NSLog(@"JSON deserialization error: %@", deserializationError.localizedDescription);
return;
}
} ];
Here is what I receive from the server:
{"photo":"�PNG\r\n\u001A\n\u0000\u0000\u0000\rIHDR\u0000\u0000\u0000:\u0000\u0000\u0000:\b\u0002\u0000\u0000\u0000n��\u007F\u0000\u0000\u001FrIDATx�}z\u0005W[y��|��..."}
But i've got an error parsing JSON: "JSON deserialization error: The operation couldn’t be completed. (Cocoa error 3840.)". I think that the problem is with the format of JSON. But guys, that write server side say that they can successfully deserialize this object. Any suggestions how to deal with this JSON?
Upvotes: 2
Views: 1210
Reputation: 2525
ImageData
can't directly transfer to NSString
,
you can do this by GMTBase64
:
Encode
NSString *imgStr = [GTMBase64 stringByEncodingData:imageData];
Decode
NSData *imageData = [GTMBase64 decodeString:imageStr];
Convert to Image
UIImage *image = [[UIImage alloc]initWithData:imageData];
Upvotes: 0
Reputation: 13222
As far as I know a JSON response must be string. The image you are getting looks like image data which is breaking the JSON parse with NSPropertyListErrorMinimum
(Cocoa error domain: 3840). The server side JSON needs to send image encoded as a base64 string. This will keep the JSON valid at client side..
You can decode the base64 encoded image to get the image data at client side. Use this NSData
category which will help you decode the base64 string to NSData
.
NSData *imageData = [NSData dataWithBase64EncodedString:base64JSONString];
// Create image with data
UIImage *image = [[UIImage alloc] initWithData:imageData];
Hope that helps!
Upvotes: 1