Default DataMember Emit

I have a .Net Web Service function that can take one line.

This function then serializes this string into JSON, but I want to serialize it if the value is not equal.

I found the following instructions:

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

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

Unfortunately, I cannot hide myValue from serialization, because "" is not the default .Net value for the string (as it is!)

One of two options:

  • There is some kind of attribute in the web service that sets the "" to null

  • There is some condition for the class

I would prefer the first, because it makes the code cleaner, but the opinion will be great.

thanks

+4
source share
2 answers

You can explicitly specify a default value (for serialization purposes) using the DefaultValueAttribute class:

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

I think you have at least a couple of options. This is an extra job, but worth it.

  • You can encapsulate a string in a reference type. Since the reference types are null if not present, this allows you to immediately know whether the string was present or not (because the type of the encapsulation reference type will be either non-null or null if the string is not empty or not).

  • The final option is to add an extra variable (possibly a boolean) that is set to OnDeserializing / OnDeserialized / OnSerializing / OnSerialized and used to track if something was actually present on the wire. You can, for example, set this extra variable to true only when you actually serialize a non-empty string and similarly

0
source

All Articles