我一直使用NSJSONSerialization
类将对象的字段转换为JSON。不幸的是,只支持NSString、NSNumber、NSArray、NSDictionary或NSNull类型。
由于我的对象有一个额外的字段,即UIImage
,我不知道该如何处理它。我相信许多人都遇到了这个常见的问题,那么最好的方法是什么呢?
我一直使用NSJSONSerialization
类将对象的字段转换为JSON。不幸的是,只支持NSString、NSNumber、NSArray、NSDictionary或NSNull类型。
由于我的对象有一个额外的字段,即UIImage
,我不知道该如何处理它。我相信许多人都遇到了这个常见的问题,那么最好的方法是什么呢?
UIImage
数据,并将其添加到json对象中。
要从UIImage获取数据,可以使用UIImagePNGRepresentation
和UIImageJPEGRepresentation
。
代码如下,NSData *imageData = UIImagePNGRepresentation(image);
NSString *base64encodedStr = base64encode(imageData);
[dict setObject:base64encodedStr forKey:@"myImage"];
//then covert dict to json object.
UIImage
数据,只需解析json对象并通过base64解码数据。NSData *imageData = UIPNGRepresentation(image);
NSString *imageString = [[NSString alloc] initWithData:imageData encoding:NSUTF8StringEncoding];
//I don't know how to use NSJSONSerialization
//[NSJSONSerialization serializeString:imageString];
NSString *base64encodedStr = [imageData base64Encoding];