Search code examples
c#asp.net-web-apidatacontractserializer

Web API - Self close tag instead of i:nil


I am using Web API with DataContract serialization. The output looks like this:

<Data>
<Status>
  <Date>2014-08-13T00:30:00</Date>
  <ID>312</ID>
  <Option>No Limitation</Option>
  <Value i:nil="true" />
</Status>
<Status>
  <Date>2014-08-13T01:00:00</Date>
  <ID>312</ID>
  <Option>No Limitation</Option>
  <Value i:nil="true" />
</Status>
<Status>
  <Date>2014-08-13T01:30:00</Date>
  <ID>312</ID>
  <Option>No Limitation</Option>
  <Value i:nil="true" />
</Status>
<Status>
  <Date>2014-08-13T02:00:00</Date>
  <ID>312</ID>
  <Option>No Limitation</Option>
  <Value i:nil="true" />
</Status>

I was able to remove all the extra namespaces by doing:

[DataContract(Namespace="")]
public class Status

But the only attribute left is the i:nil attribute. What should i do in order to remove the i:nil attribute?


Solution

  • What you want is to make the code "think" that instead of having a null value, it actually has an empty string. You can do that by being a little smart with the property getter (see below). Just remember to add a comment explaining why you're doing that so other people who will maintain the code know what's going on.

    [DataContract(Namespace = "")]
    public class Status
    {
        [DataMember]
        public DateTime Date { get; set; }
    
        [DataMember]
        public int ID { get; set; }
    
        [DataMember]
        public string Option { get; set; }
    
        private string value;
    
        [DataMember]
        public string Value
        {
            get { return this.value ?? ""; }
            set { this.value = value; }
        }
    }