How to serialize static or const member variables using JSON.NET?

It could certainly serialize the static variable if it wanted to. Serialization is done by inspecting objects and types with the Reflection APIs, and those APIs allow you to do “anything” — there is no technical reason these values cannot be serialized.

There is, however, a logical reason not to support this by default: it doesn’t make much sense. You are serializing an instance, and static or const members are not logically part of an instance but of the class as a whole.

That said, you can still serialize static member if it’s a property:

[JsonProperty]
public static int y { get; set; } // this will be serialized

And of course you can completely override the serializer’s behavior by creating a custom JsonConverter.

Leave a Comment