是否可以使用JSON.NET序列化静态属性,而无需为每个属性添加[JsonProperty]属性。 示例类:
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"
}
默认行为会跳过静态属性:
var x = JsonConvert.SerializeObject(new Settings(), Formatting.Indented);
答案 0 :(得分:8)
您可以使用自定义合约解析程序执行此操作。具体而言,您需要子类DefaultContractResolver
并覆盖GetSerializableMembers
函数:
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
属性添加到要序列化的成员列表中。
要使用它,您可以创建新的JsonSerializerSettings
对象,并将ContractResolver
设置为StaticPropertyContractResolver
的实例:
var serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new StaticPropertyContractResolver();
现在,将这些设置传递给JsonConvert.SerializeObject
,一切都应该有效:
string json = JsonConvert.SerializeObject(new Settings(), serializerSettings);
输出:
{
"IntSetting": 5,
"StrSetting": "Test str"
}
答案 1 :(得分:1)
解决此问题的更复杂方法:
解决方案1:
public class Settings
{
int intsetting { get; set; } /*= 0;*/ // commented only allowed in C# 6+
string strsetting { get; set; } /*= "";*/
public int IntSetting { get { return intsetting; } set { intsetting = value; } }
public string StrSetting { get { return strsetting; } set { strsetting = value; } }
static Settings()
{
IntSetting = 5;
StrSetting = "Test str";
}
}
解决方案2:(不太复杂)
public class Settings
{
[JsonProperty]
public static int IntSetting { get; set; }
[JsonProperty]
public static string StrSetting { get; set; }
static Settings()
{
IntSetting = 5;
StrSetting = "Test str";
}
}
将[JsonProperty]
添加到所有变量将是解决此问题的最简单方法,但是当您不想使用它时解决方案1 最适合您。< / p>