Web API: Failed to serialize the response body for content type

你。 提交于 2019-12-02 03:58:54

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!