When using JSON.Net to serialize/deserialize structs, a build-in struct type (like System.Drawing.Size) serializes to a string, whereas a custom struct type serializes to a JSON object.
For example:
using System;
using System.Drawing;
using Newtonsoft.Json;
namespace TestJsonNet
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(JsonConvert.SerializeObject(new Size(50, 50)));
Console.WriteLine(JsonConvert.SerializeObject(new Size2(50, 50)));
}
}
struct Size2
{
public int Width { get; set; }
public int Height { get; set; }
public Size2(int w, int h) : this()
{
Width = w; Height = h;
}
}
}
Outputs the following:
"50, 50"
{"Width":50,"Height":50}
I can understand the thinking behind serializing a struct to a string, since the memory layout is always the same; however, why the discrepancy when serializing a custom struct?
Also, I would (for internal legacy reasons), like to have JSON.Net serialize structs like the latter case (i.e. as JSON, not string). If it's possible, how can that be achieved?