ash84
ash84

Reputation: 817

c# JSON Serialization Data Member Order

[DataContract]
public class JsonTraceRecord
{
    [DataMember(Order = 0)]
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string level { get; set; }

    [DataMember(Order = 1)]
    public string type { get; set; }

    [DataMember(Order = 2)]
    public string time { get; set; }

    [DataMember(Order = 3)]
    public string requestId { get; set; }

    [DataMember(Order = 4)]
    public string message { get; set; }


    [DataMember(Order = 5)]
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string header { get; set; }


    [DataContract]
    public class RequestRecord : JsonTraceRecord
    {
        [DataMember ]
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string method { get; set; }
    }

    [DataContract]
    public class ResponseRecord : JsonTraceRecord
    {
        [DataMember]
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string status { get; set; } 
    }

}

I want to this order..

level, type, time, requestId, message, header, [method | status]

but in case of RequestRecord

method, level, type, time, requestId, message, header

and in case of ResponseRecord

status, level, type, time, requestId, message, header

how to correct the order I want?

Upvotes: 1

Views: 1560

Answers (1)

WillfulWizard
WillfulWizard

Reputation: 5409

The following rules govern the order:

If a data contract type is a part of an inheritance hierarchy, data members of its base types are always first in the order.

Next in order are the current type’s data members that do not have the Order property of the DataMemberAttribute attribute set, in alphabetical order.

Next are any data members that have the Order property of the DataMemberAttribute attribute set. These are ordered by the value of the Order property first and then alphabetically if there is more than one member of a certain Order value. Order values may be skipped.

https://msdn.microsoft.com/en-us/library/ms729813.aspx

Oddly, the first rule seems to be ignored in your case, and the order you're getting is coming from the second rule.

So, have you tried setting [DataMember(Order = 10)] on each of Method and Status?

At first I thought you were having trouble with the order coming from the first rule. Just in case, here are the options I thought of to get around that rule:

  1. Accept the order as is.
  2. Add the properties to the base class, and ensure they are not serialized out if null. This is not a great solution, since it means the parent class knows too much about the children.
  3. Create a wrapper class such as ResponseRecordJSON for each that simply passes along all the properties of the inner class, and set the correct serialization order on it. Again, this is not ideal as you have to correctly reference instead of ResponseRecord.

Upvotes: 1

Related Questions