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?