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

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

    Just as a quick add-on to Brian Rogers's answer, in the (somewhat common?) case of the Size being an internal variable inside a larger class you are serializing / de-serializing. This might be trivial, but as I'm new to Newtonsoft's JSON parser, it took me some googling to find the right tag.

    Long story short, if your class uses Size as part of it and you'd like to use the above converter. Assume you have the class called Agent that has Size as part of it's definitions, you should do something like this:

    public class Agent
    {
            [JsonConverter(typeof(SizeJsonConverter))]
            public Size size = new Size();
            public long time_observed = 0;
    }

    Notice that the the tag name is still JsonConverter, but the type of it is the converter sub-class you created from the snippet of the accepted answer.

    Hope that saves some newbie like me a few minutes of Googling.

提交回复
热议问题