Last post Jul 08, 2014 11:51 PM by damienBod
Jul 07, 2014 02:02 PM|adrianhara|LINK
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;
Unfortunately this results in my converter never getting called. I'm using WebApi 2.1 in a MVC 5.1 project.
Jul 07, 2014 02:06 PM|adrianhara|LINK
It probably has something to do with me not doing the configuration correctly. I'm doing it in Global.asax first thing in Application_Start().
That looks to be wrong though, because I noticed that doing this "jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();" also has no effect.
Jul 07, 2014 03:14 PM|damienBod|LINK
It's probably alright. You need to remove the default json serializer. This gets called first before yours.
config.Formatters.Insert(0, new yourSerializer());
or you could just extend the default
Jul 07, 2014 05:06 PM|adrianhara|LINK
Thanks for the answer Damien.
I'm not sure I understand. I didn't implement a custom serializer, only a converter, do I have to implement a serializer to replace the default one as well? The post you linked also doesn't seem to implement any custom serializer, in fact it pretty much
does what I did. Am I missing something?
Jul 07, 2014 11:12 PM|damienBod|LINK
try changing it then in the web api config method, in the app start folder. This is getting called by the OWIN startup method in the Startup class I'm guessing
Jul 08, 2014 01:38 PM|adrianhara|LINK
For reference the problem was that I was returning Json() from the action, and apparently it doesn't take these settings into account. Using Content() or Ok() works fine!
See also http://stackoverflow.com/questions/24620110/webapi-custom-jsonconverter-not-called
Jul 08, 2014 11:51 PM|damienBod|LINK
If you use System.Web.Helpers.Json then you have to provide settings for this as well like you explained. If you use OK() or Content(), this uses the configured formatter in Web API. Do you have to serialize the result manually? Can you not let the Web API
do this for you?