2012-11-07 6 views
55

ASP.NET Web APIは、オブジェクトをシリアライズするためにJson.NETをネイティブに使用することを理解していますが、使用するオブジェクトとしてJsonSerializerSettingsオブジェクトを指定する方法はありますか?MVC 4 Web APIでJson.NET用のカスタムJsonSerializerSettingsを設定するには?

たとえば、typeの情報をシリアル化されたJSON文字列に含めるにはどうすればよいですか?通常、私は.Serialize()呼び出しに設定を注入しますが、Web APIはそれを自動的に行います。私は手動で設定を挿入する方法を見つけることができません。

答えて

97

は、HttpConfigurationオブジェクトのFormatters.JsonFormatter.SerializerSettingsプロパティを使用してカスタマイズできます。あなたは、各JsonConvertためJsonSerializerSettingsを指定することができます

protected void Application_Start() 
{ 
    HttpConfiguration config = GlobalConfiguration.Configuration; 
    config.Formatters.JsonFormatter.SerializerSettings.Formatting = 
     Newtonsoft.Json.Formatting.Indented; 
} 
+30

あなたはコントローラやアクションごとにこれを行うことができますか? – Chazt3n

+1

これは、HangFireがインストールされたASP.NETアプリで動作することができません。間違ったlibararyなどを参照しています。デフォルト設定で他の答えを使用しなければなりませんでした。 – ppumkin

31

、あなたはグローバルなデフォルトを設定することができます。

たとえば、あなたはのApplication_Start()メソッドでそれを行うことができます。過負荷と

シングルJsonConvert

// Option #1. 
JsonSerializerSettings config = new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore }; 
this.json = JsonConvert.SerializeObject(YourObject, Formatting.Indented, config); 

// Option #2 (inline). 
JsonConvert.SerializeObject(YourObject, Formatting.Indented, 
    new JsonSerializerSettings() { 
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore 
    } 
); 

Global.asax.csでApplication_Start()のコードでを設定するグローバル:

JsonConvert.DefaultSettings =() => new JsonSerializerSettings { 
    Formatting = Newtonsoft.Json.Formatting.Indented, 
    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore 
}; 

参考:https://github.com/JamesNK/Newtonsoft.Json/issues/78

+3

FWIW、2番目の方法は、私が最初に試したもので、*動作しませんでした。 'JsonConvert.DefaultSettings'で設定された設定が観測されていなかったので、[carlosfigueiraの答え](http://stackoverflow.com/a/13274791/44853)のように' HttpConfiguration'を使う必要がありました。 –

+1

私のケースでは、グローバル設定usgin 'JsonSerializerSettings'が私にとってうまくいきました。私はHttpCOnfigurationを動作させることができませんでしたが、別のアセンブリメソッド(Hangifre)を使用して戻ってきた理由がわかりません。 – ppumkin

+0

隠しフィールド 'formHiddenField.Value = JsonConvert.SerializeObject(listaCursos、Formatting.Indented、jsonSerializerSettings);を使用して、' var data = $( '#formHiddenField')の値を取得するためにJQueryを使用できますか? – Kiquenet

2

回答がありますこれを2行追加するGlobal.asax.cs Application_StartメソッドにFコード

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; 
json.SerializerSettings.PreserveReferencesHandling = 
    Newtonsoft.Json.PreserveReferencesHandling.All; 

参考:Handling Circular Object References

関連する問題