How to de/serialize System.Drawing.Size to object using JSON.Net?
c#, json, json.net, serialization
Solution
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<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
Problem
I have absolutely no idea how to do this. Sample class that I use: ``` class MyClass { private Size _size = new Size(0, 0); [DataMember] public Size Size { get { return _size; } set { _size = value; } } } ``` This getting serialized to `{size: "0, 0"}`. What I need is `{size: {width: 0, height: 0}}`. Any help is appreciated, thanks.