I have a class that I serialize to JSON in C# and post to a RESTful web service. I have a requirment that if one field is filled out another field not be present. The service errors if both fields are serialized into the JSON object. My class looks like this:
[DataContract(Name = "test-object")]
public class TestObject
{
[DataMember(Name = "name")]
public string Name { get; set; }
// If string-value is not null or whitespace do not serialize bool-value
[DataMember(Name = "bool-value")]
public bool BoolValue { get; set; }
// If string-value is null or whitespace do not serialize it
[DataMember(Name = "string-value")]
public string StringValue { get; set; }
}
As noted in the comments, if StringValue has a value don't put BoolValue in the JSON object. If StringValue is blank, don't put in StringValue but instead put in BoolValue.
I found how to do this with XML serialization, but cannot find a way this works with JSON serialization. Is there conditional JSON serialization on C#?