I have a generated WCF client with class similar to the sample below
public partial class SampleClass
{
private bool costFieldSpecified;
private decimal costField;
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool CostFieldSpecified
{
get
{
return this.costFieldSpecified;
}
set
{
this.costFieldSpecified = value;
}
}
[System.Xml.Serialization.XmlElementAttribute(Order=0)]
public string Cost
{
get
{
return this.costField;
}
set
{
this.costField = value;
}
}
}
In my unit test, I instantiate an instance of SampleClass with a value of Cost field but without setting the CostFieldSpecified to true. When I serialise it to Json string, the Cost field’s value is 0 instead of the value I set it. I then realise that if I set the CostFieldSpecified to true, the serialised Json string will have the correct Cost value that I set. For testing, this could be tedious having to set the Specified fields to true if your class has lots of those.
To solve this, I add a Json Contract Resolver to ignore the Specified field when serialising.
public static class JsonContractResolvers
{
public static readonly DefaultContractResolver IgnoreIsSpecifiedMembersResolver =
new DefaultContractResolver { IgnoreIsSpecifiedMembers = true };
}
This is how to use it
var jsonSerialiserSettings = new JsonSerializerSettings { ContractResolver = JsonContractResolvers.IgnoreIsSpecifiedMembersResolver };
var json = JsonConvert.SerializeObject(testObject, Formatting.Indented, jsonSerialiserSettings);