Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Json.NET as default deserializer in an ASP.NET MVC 3+ application?

There're a lot of resources on how to substitute the Json.NET library as the default serializer in ASP.NET MVC apps, but, for the life of me, I can't find a single resource on how to set it as the default deserializer.

To illustrate that a bit, here's some template code:

                              // how to use Json.NET when deserializing
                              // incoming arguments?
                                    V
public ActionResult SomeAction ( Foo foo ) {

    // this piece of code has lots of resources
    // on how to override the default Javascript serializer
    return Json(new Bar());

}

How do I tell my application to use Json.NET when deserializing incoming parameters in controller actions, say, from a jQuery AJAX call?

$.ajax({
    type : 'POST',
    data : { foo : 'bar' }
});

I've tried adapting MediaTypeFormatters into my code by adjusting this resource from Rick Strahl, but that didn't work either. Note that I'm not in a WebAPI environment --- but I expect that one solution that works on a normal Controller should work (albeit with minimal adjustments) in an ApiController.

like image 768
Richard Neil Ilagan Avatar asked Sep 11 '12 17:09

Richard Neil Ilagan


People also ask

How do I use JSON deserializer?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

How do you serialize and deserialize an object in C# using JSON?

To serialize a . Net object to JSON string use the Serialize method. It's possible to deserialize JSON string to . Net object using Deserialize<T> or DeserializeObject methods.

Is JSON net the same as Newtonsoft JSON?

Json.NET vs Newtonsoft. Json are the same thing. You must be trying to use the same code with different versions of Json.NET.


1 Answers

You'll need to implement a custom ValueProviderFactory and remove the standard JsonValueProviderFactory.

There's some example code here: http://json.codeplex.com/discussions/347099 however reading through the comments, i'm not 100% sure that it will properly handle dictionaries.

like image 152
Fatal Avatar answered Sep 23 '22 17:09

Fatal