WebApi custom JsonConverter not called

*爱你&永不变心* 提交于 2020-01-04 02:55:16

问题


I implemented a custom JsonConverter for Guids.

If I declare it on the properties (of type Guid) of the class serialized like so

[JsonConverter(typeof(JsonGuidConverter))]

then it gets called and works fine.

However, I'd like to use it "automatically", without needed the attributes, so I do this:

var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
jsonFormatter.SerializerSettings.Converters.Add(new JsonGuidConverter());

Unfortunately this results in my converter never getting called. I'm using WebApi 2.1 in a MVC 5.1 project.

Any ideas?

Edit: here is the converter code

public class JsonGuidConverter : JsonConverter
{
    public override bool CanRead
    {
        get
        {
            // We only need the converter for writing Guids without dashes, for reading the default mechanism is fine
            return false;
        }
    }
    public override bool CanWrite
    {
        get
        {
            return true;
        }
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Guid) || objectType == typeof(Guid?);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
    {
        // We declared above CanRead false so the default serialization will be used
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
    {
        if (value == null || Guid.Empty.Equals(value))
        {
            writer.WriteValue(string.Empty);
        }
        else
        {
            writer.WriteValue(((Guid)value).ToStringNoDashes());
        }
    }
}

Additional note, not even the CanRead/CanWrite properties and CanConvert method are called when trying to use it by adding it to the converters collection.

Maybe it has something to do with how I return data from the webapi controller?

public async Task<IHttpActionResult> GetSettings()
{
    ...
    return Json(something);
}

回答1:


Since your are using formatters, do not use Json(something) when returning from action, but rather use Content(something) in this case. The Content helper will honor the formatters' settings.

I agree that Json helper is confusing here and something which I wished we never included in our product.



来源:https://stackoverflow.com/questions/24620110/webapi-custom-jsonconverter-not-called

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