WebApi Json格式化


兩種轉換方式:

1.全局設定,針對GlobalConfiguration.Configuration.Formatters.JsonFormatter做設定,位於Global.asax 如:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
json.SerializerSettings.Culture = new CultureInfo("it-IT");

2.單獨設定,針對單獨Action 代碼段如:

var formatter = new JsonMediaTypeFormatter();
var json = formatter.SerializerSettings;
json.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
json.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
json.Formatting = Newtonsoft.Json.Formatting.Indented;
json.ContractResolver = new CamelCasePropertyNamesContractResolver();
json.Culture = new CultureInfo("it-IT");
return Request.CreateResponse(HttpStatusCode.OK, result, formatter);

參考來源:http://tostring.it/2012/07/18/customize-json-result-in-web-api/

這篇文章既然看懂了,看來英文也不是不能學會!加油!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM