DataMember Emit Default Value
Asked Answered
B

2

5

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

Bigamist answered 4/5, 2011 at 11:33 Comment(0)
P
7

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 = ""
}
Pajamas answered 2/7, 2013 at 18:15 Comment(0)
C
0

I think you have at least a couple of options here. It's extra work but worth it.

  • You can encapsulate the string in a reference type. Since reference types are null if not present, that lets you know right away if a string was present or not (because the encapsulating reference type would be either non-null or null, if the string is non-empty or not.)

  • A final option you have is to add an extra complementary variable (perhaps a boolean) that is set on OnDeserializing/OnDeserialized/OnSerializing/OnSerialized and use this to track whether or not something was actually present on the wire. You might, for example, set this complementary variable to true only when you're actually serializing out a non-empty string and similarly

Counterpressure answered 26/4, 2012 at 17:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.