How do I Serialize object to json using json.net which contains an image property

前端 未结 2 455
情深已故
情深已故 2021-01-03 06:17

I have an object with a number of public properties where one is of type image. I am trying to serialise this using json.net and assume that I will need to base64 encode th

相关标签:
2条回答
  • 2021-01-03 06:37

    Json.NET has no idea about what is Image, so you have to help it a bit, for example by using a converter (BinaryConverter is not for images):

    public class ImageConverter : JsonConverter
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
            var base64 = (string)reader.Value;
            // convert base64 to byte array, put that into memory stream and feed to image
            return Image.FromStream(new MemoryStream(Convert.FromBase64String(base64)));
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
            var image = (Image) value;
            // save to memory stream in original format
            var ms = new MemoryStream();
            image.Save(ms, image.RawFormat);
            byte[] imageBytes = ms.ToArray();
            // write byte array, will be converted to base64 by JSON.NET
            writer.WriteValue(imageBytes);
        }
    
        public override bool CanConvert(Type objectType) {
            return objectType == typeof(Image);
        }
    }
    
    public class Person
    {
        public string name { get; set; }
    
        public int age { get; set; }
    
        [JsonConverter(typeof(ImageConverter))]
        public Image photo { get; set; }
    
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this);
        }
    }
    

    Then it will both serialize and deserialize your class just fine.

    0 讨论(0)
  • 2021-01-03 06:49

    I would recommend in this case to convert the image to base64 and then serialize it, here an example of how to do it in C#: Convert Image to Base64

    0 讨论(0)
提交回复
热议问题