如何将UIImage序列化为JSON?

use*_*966 7 ios nsjsonserialization

我在用

imageData = UIImagePNGRepresentation(imgvw.image);

并在发布时

[dic setObject:imagedata forKey:@"image"]; 
Run Code Online (Sandbox Code Playgroud)

NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&theError];

现在应用程序由于未捕获的异常而崩溃终止应用程序' NSInvalidArgumentException',原因:'JSON写入中的无效类型(NSConcreteMutableData)

Cod*_*da1 11

您需要将UIImage转换为NSData,然后将该NSData转换为NSString,它将是您数据的base64字符串表示形式.

一旦从NSData*获得NSString*,就可以将其添加到密钥@"image"的字典中

要将NSData转换为base64类型NSString*,请参阅以下链接: 如何在iphone-sdk上执行base64编码?

以更伪的方式,该过程将如下所示

UIImage *my_image; //your image handle
NSData *data_of_my_image = UIImagePNGRepresentation(my_image);
NSString *base64StringOf_my_image = [data_of_my_image convertToBase64String];

//now you can add it to your dictionary
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:base64StringOf_my_image forKey:@"image"];

if ([NSJSONSerialization isValidJSONObject:dict]) //perform a check
{
        NSLog(@"valid object for JSON");
        NSError *error = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];


        if (error!=nil) {
            NSLog(@"Error creating JSON Data = %@",error);
        }
        else{
            NSLog(@"JSON Data created successfully.");
        }
}
else{
        NSLog(@"not a valid object for JSON");
    }
Run Code Online (Sandbox Code Playgroud)