adrian h.
adrian h.

Reputation: 3026

WebApi custom JsonConverter not called

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);
}

Upvotes: 3

Views: 3120

Answers (1)

Kiran
Kiran

Reputation: 57949

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.

Upvotes: 6

Related Questions