Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataMember Emit Default Value

I have a .Net Web Service function that can accept one string.

That function will then serialize that string to JSON, but I only want to serialize it if it's value is not "".

I found these instructions:

http://msdn.microsoft.com/en-us/library/aa347792.aspx

[DataContract]
public class MyClass
{
   [DataMember (EmitDefaultValue=false)]
   public string myValue = ""
}

Unfortunatelly I can not hide the myValue from the serialization because "" is not the .Net default value for a string (how dumb is that!)

One of two option ocurred

  1. On the web service have some kind of attribute that sets the "" to null

  2. Have some condition on the class

I would prefer the 1st because it makes the code cleaner but an opinion would be great.

Thanks

like image 790
RedEagle Avatar asked May 04 '11 11:05

RedEagle


1 Answers

You can explicitly set what the default value is (for the purposes of serialization) using the DefaultValueAttribute class:

[DataContract]
public class MyClass
{
    [DataMember (EmitDefaultValue=false)]
    [DefaultValue("")]
    public string myValue = ""
}
like image 139
Steve Greatrex Avatar answered Sep 30 '22 13:09

Steve Greatrex