Send picture as json
Sometimes you might send a picture as a json file to a server on your iPhone or iPad app. There are many ways to accomplish this task and I would like to discuss one of the ways we are using here at Walden Systems, because we believe this is the most straightforward method to create a json file from a picture.
Strategy to serialize picture to json is fairly simple: First, we need to use NSDictionary to hold the data. Second, we need to convert the picture to base64 encoded string. Third, we need to add picture string to NSDictionary. Fourth, we need to convert NSDictionary to json.
Here are actual code samples:
The first thing you need to do is create a new NSDictionary to , to do so, use the following line:
NSDictionary * someDict ;
Then you convert the picture to a base64 encoded string :
someString = [ UIImageJPEGRepresentation ( SOMEPICTURE, 1 )base64EncodedStringWithOptions : 0 ] ;
Then you will need to add value to the dictionary :
someDict = [NSDictionary dictionaryWithObjectsAndKeys :[ someString,@"KEY",nil ] ;
Finally, you can convert the NSDictionary to json :
1 NSData * jsonData ; 2 jsonData = [NSJSONSerialization dataWithJSONObject : someDict options : kNilOptions error : nil ] ;
So, this is how a final code for onverting picture to json data will look like:
1 NSDictionary * someDict ; 2 NSString * someString ; 3 NSData * jsonData ; 4 5 someString = [ UIImageJPEGRepresentation ( SOMEPICTURE, 1 )base64EncodedStringWithOptions : 0 ] ; 6 someDict = [NSDictionary dictionaryWithObjectsAndKeys :[ someString,@"KEY",nil ] ; 7 jsonData = [NSJSONSerialization dataWithJSONObject : someDict options : kNilOptions error : nil ] ;