How to serialize static properties in JSON.NET without adding attribute [JsonProperty]

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

public class Settings { public static int IntSetting { get; set; } public static string StrSetting { get; set; } static Settings() { IntSetting = 5; StrSetting = "Test str"; } } 

Expected Result:

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

The default behavior skips static properties:

 var x = JsonConvert.SerializeObject(new Settings(), Formatting.Indented); 
+5
source share
2 answers

You can do this with a custom recognizer. In particular, 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; } } 

Here, all we do is call the base implementation of GetSerializableMembers , and then add the public static properties to our list of members for serialization.

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

 var serializerSettings = new JsonSerializerSettings(); serializerSettings.ContractResolver = new StaticPropertyContractResolver(); 

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

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

Conclusion:

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

Example: https://dotnetfiddle.net/pswTJW

+6
source

A more complicated way to solve this problem:

Solution 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"; } } 

Solution 2: (less complicated)

 public class Settings { [JsonProperty] public static int IntSetting { get; set; } [JsonProperty] public static string StrSetting { get; set; } static Settings() { IntSetting = 5; StrSetting = "Test str"; } } 

Adding [JsonProperty] to all variables would be the easiest way to resolve this issue, but if you do not want to use it, Solution 1 is best for you.

+1
source

All Articles