1

I have been using DataContractJsonSerializer succesfully to serialize an object into json. The great thing about this is that I can work with optional fields (that may or maynot be serialized). For example

[DataContract()]
public class aClass
{
  [DataMember()]
  public int member1;
  [DataMember()]
  public int member2;
  [DataMember(EmitDefaultValue=false)]
  public int member3;
}

In this case, when I instantiate an object of class aClass I can set member1 to be 1 and member 2 to be 2 and member3 to be 3. When I serialize it, I get the corresponding JSON string. On the other hand if I only set member1 and member2, the serializer ignores member3 when generating the JSON string. This is very useful and it works not only in ints but lists, objects, etc.

Now, I have not tried it, but I think that the serializer will ignore member3 not only when not set, but also when set to the default (in the int case the default would be 0). So as long as member3 is 1 or 2 or 3, it gets serialized. So far that was the desirable behavior.

Here comes my problem.

I would like for member3 to be serialized when set to 0, or 1, 2, 3. And not serialized otherwise. (for example when not set)

Is this even possible? How can this be achieved?

KansaiRobot
  • 7,564
  • 11
  • 71
  • 150
  • Conditional serialization isn't supported in the general case by the data contract serializers. For workarounds see e.g. [How to conditionally avoid property from serializing in WCF?](https://stackoverflow.com/q/48267916) or [Dynamically ignore data members from getting serialized](https://stackoverflow.com/q/21091785) – dbc Sep 11 '18 at 07:52

1 Answers1

0

I finally found a way to do what I was asking. Yes, at first I did a hack to be able to serialize 0, but it was a hack involving keeping other variables (bool setTo0=false) but then I found there is a cleaner easier way.

It is using Nullable Types. When you declare an int as a nullable type, it will serialize it even when set to the default 0. The only time it will not serialize it is when originally set to null (yes, an int can be set to Null in this case).

KansaiRobot
  • 7,564
  • 11
  • 71
  • 150