JSON.Net Struct Serialization Discrepancy

Dav*_* T. 9 c# json json.net

使用JSON.Net序列化/反序列化结构时,内置结构类型(如System.Drawing.Size)序列化为字符串,而自定义结构类型序列化为JSON对象.

例如:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出以下内容:

"50, 50"
{"Width":50,"Height":50}
Run Code Online (Sandbox Code Playgroud)

我可以理解将结构序列化为字符串的想法,因为内存布局总是相同的; 但是,序列化自定义结构时出现差异的原因是什么?

另外,我会(因为内部遗留原因),喜欢让JSON.Net序列化结构像后一种情况(即作为JSON,而不是字符串).如果有可能,怎么能实现呢?

Ber*_*ams 2

使用反射可以解决这个问题。我采用了您自己建议的解决方案的一部分,并使用反射来获取属性名称和值。

class StructConverter : JsonConverter
{
    public override void WriteJson(
        JsonWriter writer, object value, JsonSerializer serializer)
    {
        var myObject = (object)value;
        var jObject = new JObject();

        Type myType = myObject.GetType();
        IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

        foreach (PropertyInfo prop in props)
        {

            jObject.Add(prop.Name, prop.GetValue(myObject, null).ToString());
        }
        serializer.Serialize(
            writer,  jObject);
    }
Run Code Online (Sandbox Code Playgroud)

....

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsValueType;
    }
}
Run Code Online (Sandbox Code Playgroud)