Newtonsoft.Json deserializing base64 image fails

前端 未结 3 1262
甜味超标
甜味超标 2020-12-09 23:18

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 Use

3条回答
  •  借酒劲吻你
    2020-12-09 23:45

    I think that the Deserializing from Base64 to System.Drawing.Bitmap is not supported. May be you can try deserializing everything excepts the Avatar property

    EDIT FOR EDITED QUESTION

    Here is an interesting discussion on how to do that: JSON.Net Ignore Property during deserialization

    I think the best that you can do is use Regex to remove the property from the json string:

    var newJsonString = Regex.Replace(jsonString, 
                                      "(\\,)* \"Avatar\": \"[A-Za-z0-9]+\"", 
                                      String.Empty);
    

    and then deserialize this newJsonString without the Avatar property.

    Later you can parse the original json string to get the base64 and build the Bitmap

    var avatarBase64 = Regex.Match(
                            Regex.Match(json, "(\\,)* \"Avatar\": \"[A-Za-z0-9]+\"")
                                 .ToString(), 
                            "[A-Za-z0-9]+", RegexOptions.RightToLeft)
                            .ToString();
    
    ...
    
    byte[] fromBase64 = Convert.FromBase64String(avatarBase64);
    using (MemoryStream ms = new MemoryStream(fromBase64))
    {
        Bitmap img = (Bitmap)Image.FromStream(ms);
        result.Avatar = img;
    }
    

    You could improve the regular expressions or the method, but that's the basic idea.

提交回复
热议问题