So here's my situation. I'm implementing a WEB API in a WebForms app. I have a bunch of dynamic classes which are essentially dictionaries that need to use a custom JSON serialization formatter in order to work properly (because the default converter simply shows a mess of Key Value pairings).
So first I created a custom JSON converter:
/// <summary>
/// A class to convert entities to JSON
/// </summary>
public class EntityJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsSubclassOf(typeof(Entity));
}
public override bool CanRead
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// Details not important. This code is called and works perfectly.
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Details not important. This code is *never* called for some reason.
}
}
Once I have that defined I then insert it into the global JSON media type formatter:
// Add a custom converter for Entities.
foreach (var formatter in GlobalConfiguration.Configuration.Formatters)
{
var jsonFormatter = formatter as JsonMediaTypeFormatter;
if (jsonFormatter == null)
continue;
jsonFormatter.SerializerSettings.Converters.Add(new EntityJsonConverter());
}
And lastly, my test API (there will be many more added in the future, I'm just trying to test out the system for now, "Contact" inherits from "Entity"):
public class ContactController : ApiController
{
public IEnumerable<Contact> Get()
{
// Details not important. Works perfectly.
}
[HttpPost]
public bool Update(Contact contact)
{
// Details not important. Contact is always "null".
}
}
So here's what I'm seeing when I debug:
Web Site Calls "get":
Web Site Calls "update":
I'm utterly perplexed. I don't understand why this works when serializing, but the entire process seems to just skip my custom converter when trying to deserialize. Anyone have any ideas what I'm doing wrong?
Thanks!
Ah geez. Now I feel dumb.
... I wasn't sending JSON in the post data. I was accidentally sending a jumble of text. Whoops...
Nevermind!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With