I am working on a website that will post a JSON object (using jQuery Post method) to the server side.
{
\"ID\" : 1,
\"FullName\" : {
\"First
After some research, I found Takepara's solution to be the best option for replacing the default MVC JSON deserializer with Newtonsoft's Json.NET. It can also be generalized to all types in an assembly as follows:
using Newtonsoft.Json;
namespace MySite.Web
{
public class MyModelBinder : IModelBinder
{
// make a new Json serializer
protected static JsonSerializer jsonSerializer = null;
static MyModelBinder()
{
JsonSerializerSettings settings = new JsonSerializerSettings();
// Set custom serialization settings.
settings.DateTimeZoneHandling= DateTimeZoneHandling.Utc;
jsonSerializer = JsonSerializer.Create(settings);
}
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
object model;
if (bindingContext.ModelType.Assembly == "MyDtoAssembly")
{
var s = controllerContext.RequestContext.HttpContext.Request.InputStream;
s.Seek(0, SeekOrigin.Begin);
using (var sw = new StreamReader(s))
{
model = jsonSerializer.Deserialize(sw, bindingContext.ModelType);
}
}
else
{
model = ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, bindingContext);
}
return model;
}
}
}
Then, in Global.asax.cs, Application_Start():
var asmDto = typeof(SomeDto).Assembly;
foreach (var t in asmDto.GetTypes())
{
ModelBinders.Binders[t] = new MyModelBinder();
}