JSON.Net Struct Serialization Discrepancy

情到浓时终转凉″ 提交于 2019-12-05 02:27:55

Using reflection you could solve this problem. I took part of the solution you suggested yourself and used reflection to get the property names and values.

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);
    }

....

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsValueType;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!