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

前端 未结 3 403
面向向阳花
面向向阳花 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:35

    You can use JsonProperty, instead of force each individual property into json result everytime.

    public class MyClass
    {
        [JsonProperty("size")]
        public Size size;
    }
    

    And this is your Size class

    public class Size
    {
        public Size(int w, int h)
        {
            this.Width = w;
            this.Height = h;
        }
    
        [JsonProperty("width")]
        public int Width
        {
            get;
            set;
        }
        [JsonProperty("height")]
        public int Height
        {
            get;
            set;
        }
    }
    

    And this is how you access it

            MyClass w = new MyClass{ size = new Size(5, 7) };
            string result = JsonConvert.SerializeObject(w);
    

    This is what you get

    {"Size":{"width":5,"height":7}}
    

    This way, everytime you add new property in your Size class or even MyClass class, you just need put the JsonProperty attribute on top of it.

提交回复
热议问题