Here is a simple JsonConverterone you can use to serialize the System.Drawing.Sizeway 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 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 produce the following result:
{"Size":{"width":80,"height":24}}
Desicialization works the same; pass the converter instance to DeserializeObject<T>:
string json = @"{""Size"":{""width"":80,""height"":24}}";
MyClass c = JsonConvert.DeserializeObject<MyClass>(json, new SizeJsonConverter());
Console.WriteLine(c.Size.Width + "x" + c.Size.Height);
Output:
80x24