OGeek|极客世界-中国程序员成长平台

标题: ios - 使用 NSJSONSerialization 从 json 反序列化图像 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 14:38
标题: ios - 使用 NSJSONSerialization 从 json 反序列化图像

我正在尝试使用 NSJsonSerialization 反序列化来自服务器的 JSON。服务器返回一个转换为字符串的 png 图像。 这是我的代码:

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

这是我从服务器收到的信息:

{"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��|��..."}

但我在解析 JSON 时出错:“JSON 反序列化错误:无法完成操作。(Cocoa 错误 3840。)”。 我认为问题在于 JSON 的格式。但是那些写服务器端的人说他们可以成功地反序列化这个对象。有什么建议如何处理这个 JSON?



Best Answer-推荐答案


据我所知,JSON 响应必须是字符串。您得到的图像看起来像使用 NSPropertyListErrorMinimum 破坏 JSON 解析的图像数据(Cocoa 错误域:3840)。服务器端 JSON 需要发送编码为 base64 字符串的图像。这将使 JSON 在客户端保持有效..

您可以对 base64 编码的图像进行解码,以在客户端获取图像数据。使用this NSData category这将帮助您将 base64 字符串解码为 NSData

NSData *imageData = [NSData dataWithBase64EncodedString:base64JSONString];
// Create image with data
UIImage *image = [[UIImage alloc] initWithData:imageData];

希望有帮助!

关于ios - 使用 NSJSONSerialization 从 json 反序列化图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18825396/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4