Nathan Friend
Nathan Friend

Reputation: 12804

Custom Json.NET JsonConverter is not being called while deserializing Web.API parameter

I have a Web.API endpoint that takes an object like this as a parameter:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public UserName UserName { get; set; }
}

For example:

[Route("api/person")]
[AcceptVerbs("POST")]
public void UpdatePerson(Person person)
{
    // etc.
}

I've defined a custom JsonConverter to convert from a JSON string property to my custom UserName class:

public class UserNameJsonDeserializer : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(UserName);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return new UserName((string)reader.Value);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanRead { get { return true; } }
    public override bool CanWrite { get { return false; } }
}

I've added this JsonConverter to my global list of JsonFormatters in my Global.asax:

// Automatically dsserialize JSON strings to UserNames
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new UserNameJsonDeserializer());

When I send a request to my Web.API, the CanConvert and ReadJson methods are never called. This is how I'm calling my Web.API endpoint front my JavaScript frontend (using jQuery):

$.ajax({
    type: 'POST',
    url: 'api/person',
    data: { 
        FirstName: 'First', 
        LastName: 'Last', 
        Age: 110, 
        UserName: 'UserName',
    },
});

Why is my custom JsonConverter being ignored by Web.API?

Upvotes: 4

Views: 2451

Answers (1)

Nathan Friend
Nathan Friend

Reputation: 12804

When making your jQuery .ajax() call, you need to send you data as JSON, otherwise the Web.API won't call any JSON-related converters while deserializing the data. Try adding a JSON contentType and JSON.stringify-ing your data parameter:

$.ajax({
    type: 'POST',
    url: 'api/person',
    data: JSON.stringify({ 
        FirstName: 'First', 
        LastName: 'Last', 
        Age: 110, 
        UserName: 'UserName'
    }),
    contentType: 'application/json; charset=utf-8'
});

Upvotes: 2

Related Questions