如何在不添加[JsonProperty]属性的情况下序列化JSON.NET中的静态属性 [英] How to serialize static properties in JSON.NET without adding [JsonProperty] attribute

查看:164
本文介绍了如何在不添加[JsonProperty]属性的情况下序列化JSON.NET中的静态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不向每个属性添加[JsonProperty]属性的情况下使用JSON.NET序列化静态属性. 示例类:

Is it possible to serialize static properties with JSON.NET without adding [JsonProperty] attribute to each property. Example class:

public class Settings
    {
        public static int IntSetting { get; set; }
        public static string StrSetting { get; set; }

        static Settings()
        {
            IntSetting = 5;
            StrSetting = "Test str";
        }
    }

预期结果:

{
  "IntSetting": 5,
  "StrSetting": "Test str"
}

默认行为会跳过静态属性:

Default behavior skips static properties:

var x = JsonConvert.SerializeObject(new Settings(), Formatting.Indented);

推荐答案

您可以使用自定义合同解析器进行此操作.具体来说,您需要继承DefaultContractResolver的子类并覆盖GetSerializableMembers函数:

You can do this with a custom contract resolver. Specifically you need to subclass DefaultContractResolver and override the GetSerializableMembers function:

public class StaticPropertyContractResolver : DefaultContractResolver
{
    protected override List<MemberInfo> GetSerializableMembers(Type objectType)
    {
        var baseMembers = base.GetSerializableMembers(objectType);

        PropertyInfo[] staticMembers = 
            objectType.GetProperties(BindingFlags.Static | BindingFlags.Public);

        baseMembers.AddRange(staticMembers);

        return baseMembers;
    }
}

我们要做的就是调用GetSerializableMembers的基本实现,然后将public static属性添加到要序列化的成员列表中.

Here all we're doing is calling the base implementation of GetSerializableMembers, then adding public static properties to our list of members to serialize.

要使用它,您可以创建一个新的JsonSerializerSettings对象并将ContractResolver设置为StaticPropertyContractResolver的实例:

To use it you can create a new JsonSerializerSettings object and set the ContractResolver to an instance of the StaticPropertyContractResolver:

var serializerSettings = new JsonSerializerSettings();

serializerSettings.ContractResolver = new StaticPropertyContractResolver();

现在,将这些设置传递给JsonConvert.SerializeObject,一切都会正常进行:

Now, pass those settings to JsonConvert.SerializeObject and everything should work:

string json = JsonConvert.SerializeObject(new Settings(), serializerSettings);

输出:

{
  "IntSetting": 5,
  "StrSetting": "Test str"
}

示例: https://dotnetfiddle.net/pswTJW

这篇关于如何在不添加[JsonProperty]属性的情况下序列化JSON.NET中的静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆