Taru Taru - 4 months ago 28
C# Question

C# - Serialize Constants with DataContractJsonSerializer

I'm having the following class:

[DataContract]
class ExampleClass
{
//Properties
[DataMember(Name = "method")]
private const string method = "Example Constant";
...
...


The DataContractJsonSerializer don't seem to include the constant "method" in the JSON output.

How can I keep the member constant, and cause the class to serialize it?

Thank you.

Answer

For the JSON-output the const is not accessable at all as it´s private. However serializing a const makes no sense at all, as a const is a static member and belongs to the class itself, not to a specific instance. Therefor the serializer can´t set it on an instance as there is nothing to set on that instance.

Having said this you may wrap your constant in a property:

[DataContract]
class ExampleClass
{
    private const string method = "Example Constant"; 

    //Properties
    [DataMember(Name = "method")]
    public string Method { get; set; }

    public ExampleClass(this.Method = method; }
}

PS.: I´m not familiar with contract-serializers, but this is what you would do with an Xml-serializer. Maybe with contract-ser you can also have a get-only property thus you won´t need the extra constructor, but I´m not sure about this.