Asp.net-Mvc-3

如何在 ASP.NET MVC 3+ 應用程序中使用 Json.NET 作為預設反序列化器?

  • September 18, 2012

有很多關於如何將 Json.NET 庫替換為 ASP.NET MVC 應用程序中的預設序列化程序的資源,但是,在我的一生中,我找不到一個關於如何將其設置為預設反序列化器

為了說明這一點,這裡有一些模板程式碼:

                             // 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());

}

在反序列化控制器操作中的傳入參數(例如,來自 jQuery AJAX 呼叫)時,如何告訴我的應用程序使用 Json.NET?

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

我嘗試通過調整Rick Strahl 的此資源來MediaTypeFormatters適應我的程式碼,但這也不起作用。請注意,我不在 WebAPI 環境中 — 但我希望一種適用於正常情況的解決方案應該在.Controller``ApiController

您需要實現自定義 ValueProviderFactory 並刪除標準 JsonValueProviderFactory。

這裡有一些範常式式碼:http: //json.codeplex.com/discussions/347099但是閱讀評論,我不能 100% 確定它會正確處理字典。

引用自:https://stackoverflow.com/questions/12374991