How to de/serialize System.Drawing.Size to object using JSON.Net?

前端 未结 3 374
面向向阳花
面向向阳花 2021-01-13 07:10

I have absolutely no idea how to do this.

Sample class that I use:

class MyClass
{

    private Size _size = new Size(0, 0);

    [DataMember]
    pu         


        
3条回答
  •  北海茫月
    2021-01-13 07:49

    Here is a simple JsonConverter you can use to make System.Drawing.Size serialize the way you want:

    using System;
    using System.Drawing;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
    public class SizeJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(Size));
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            Size size = (Size)value;
            JObject jo = new JObject();
            jo.Add("width", size.Width);
            jo.Add("height", size.Height);
            jo.WriteTo(writer);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject jo = JObject.Load(reader);
            return new Size((int)jo["width"], (int)jo["height"]);
        }
    }
    

    To use the converter, you just need to pass an instance of it to JsonConvert.SerializeObject as shown below:

    MyClass widget = new MyClass { Size = new Size(80, 24) };
    string json = JsonConvert.SerializeObject(widget, new SizeJsonConverter());
    Console.WriteLine(json);
    

    This will give the following output:

    {"Size":{"width":80,"height":24}}
    

    Deserialization works the same way; pass an instance of the converter to DeserializeObject:

    string json = @"{""Size"":{""width"":80,""height"":24}}";
    MyClass c = JsonConvert.DeserializeObject(json, new SizeJsonConverter());
    Console.WriteLine(c.Size.Width + "x" + c.Size.Height);
    

    Output:

    80x24
    

提交回复
热议问题