Newtonsoft.Json反序列化的base64图像失败 [英] Newtonsoft.Json deserializing base64 image fails

查看:2002
本文介绍了Newtonsoft.Json反序列化的base64图像失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Newtonsoft.Json反序列化从我的web服务的输出对象。 它工作得很好,直到我添加了一个位图属性上我的课(名为用户)举行的化身。

I'm using Newtonsoft.Json to deserialize the output from my webservice to an object. It worked fine until I added a Bitmapproperty to my class (named User) to hold an avatar.

该web服务返回的PROPERT为Base64字符串,这是符合市场预期。 问题是,当我尝试转换回JSON从WS到列表<使用者> ,一个 JsonSerializationException 是扔在了code此块:

The webservice is returning that propert as a Base64 string, which is as expected. The problem is when I try to convert back the JSON from the WS to a List<User>, a JsonSerializationException is thrown in this block of code:

// T is IList<User>
response.Content.ReadAsStringAsync().Proceed(
    (readTask) =>
    {
        var json = ((Task<string>)readTask).Result;
        var result = JsonConvert.DeserializeObject<T>(json); //<-- it fails here

         // do stuff! 
     });

这是异常的输出是:

Error converting value "System.Drawing.Bitmap" to type 'System.Drawing.Bitmap'. Path '[2].Avatar

和着眼于内部异常:

{"Could not cast or convert from System.String to System.Drawing.Bitmap."}

很显然,它无法解析Base64的字符串,但目前还不清楚这是为什么。

It's clear that it fails to parse the Base64 string, but it's not clear why.

任何想法/解决方法吗?

Any ideas/workaround?

修改 我知道我可以使用 Convert.FromBase64String 得到一个字节数组,并从加载一个位图。然后我想更新我的问题想请教一下我怎么可以跳过或手动解析的领域。 我想避免,不必手动解析所有的JSON。 这甚至可能?

EDIT I know I can use Convert.FromBase64String do get a byte array and load a bitmap from that. Then I'd like to update my question to ask about how can I skip or manually parse only that field. I would like to avoid, having to manually parse all the JSON. Is this even possible?

编辑2 我发现了问题的根源:JSON没有被正确的web服务序列化(我不知道为什么)。我认为,<一个href="http://stackoverflow.com/questions/15529904/different-behaviour-in-response-if-acceptapplication-json-is-specified">this是一个有些不同的问题,但是没有。我的web服务简单地返回一个字符串System.Drawing.Bitmap而不是它的base64内容。因此, JsonSerializationException

EDIT 2 I found out the root problem: JSON is not being correctly serialized in webservice (and I fail to see why). I thought that this was a somewhat different issue, but no. My webservice is simply returning a string "System.Drawing.Bitmap" instead of its base64 content. Hence the JsonSerializationException.

我一直未能解决这个问题,我已经找到了唯一的解决办法是把我的领域成字节[]

I have been unable to solve that issue, the only solution I've found is to turn my field into a byte [].

推荐答案

阅读字段作为字符串,

使用转换为字节数组 Convert.FromBase64String

使用获得的图像 Bitmap.FromStream(新的MemoryStream(字节阵列));

修改

您可以用自定义的帮助下进行图像序列化/反序列化的

You can perform image serialization/deserialization with the help of a custom converter

public class AClass
{
    public Bitmap image;
    public int i;
}

Bitmap bmp = (Bitmap)Bitmap.FromFile(@"......");
var json = JsonConvert.SerializeObject(new AClass() { image = bmp, i = 666 }, 
                                       new ImageConverter());

var aclass = JsonConvert.DeserializeObject<AClass>(json, new ImageConverter());

这是 ImageConverter

public class ImageConverter : Newtonsoft.Json.JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Bitmap);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var m = new MemoryStream(Convert.FromBase64String((string)reader.Value));
        return (Bitmap)Bitmap.FromStream(m);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        Bitmap bmp = (Bitmap)value;
        MemoryStream m = new MemoryStream();
        bmp.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);

        writer.WriteValue(Convert.ToBase64String(m.ToArray()));
    }
}

这篇关于Newtonsoft.Json反序列化的base64图像失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆