I am working with ASP.NET MVC 5 Web Api.
I am having existing application with many api\'s. Recently I have implemented custom JsonConverter which will convert Date as p
The problem looks to be that, in certain situations, you are returning from WriteJson()
without writing anything, specifically when customType.TimeZone == null
:
var customType = (CustomType)value;
if (customType == null || null== customType.TimeZone) return;
Doing so will result in an invalid JSON object, because the property name will already have been written by the caller, resulting in:
{ "customType": }
Trying to do this results in the exception you are seeing.
Instead, you need to prevent the property itself from being serialized. That's not possible in the converter however, it needs to be done in the containing type.
To avoid serializing a property with a null value, you should set NullValueHandling = NullValueHandling.Ignore
in serializer settings, or on the property itself:
public class ContainerClass
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public CustomType CustomType { get; set; }
}
To prevent serializing your property when its TimeZone
property is null, you should use conditional property serialization by adding a ShouldSerializeXXX()
method to the containing type, where XXX
exactly matches your property name:
public class ContainerClass
{
public CustomType CustomType { get; set; }
public bool ShouldSerializeCustomType()
{
return CustomType != null && CustomType.TimeZone != null;
}
}