在RestFul風格盛行的年代,對接接口大多數人會選擇使用JSON,XML和JSON的對比傳送(),看看這位博主是怎麼說的,雖然最後沒有說完,我想大概也能略微解決心中的疑惑。
1.其實要想讓WebAPI 回傳JSON格式的資料很簡單,只要在ConfigureWebapi方法中設定一下即可。先前需要引用兩個命名空間。
using Newtonsoft.Json.Serialization;using System.Linq;
2.核心程式碼如下:
var json = config.Formatters.JsonFormatter;// 解决json序列化时的循环引用问题json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;// 移除XML序列化器config.Formatters.Remove(config.Formatters.XmlFormatter);//设置序列化方式为驼峰命名法var jsonFormatter = config.Formatters.OfType<system.net.http.formatting.jsonmediatypeformatter>().First(); jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();// Web API 路由config.MapHttpAttributeRoutes();</system.net.http.formatting.jsonmediatypeformatter>
#完整程式碼如下:
/// <summary>/// 配置WebApi/// </summary>/// <param>public void ConfigureWebapi(IAppBuilder app) {//创建一个HTTP的实例配置var config = new HttpConfiguration();var json = config.Formatters.JsonFormatter;// 解决json序列化时的循环引用问题json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;// 移除XML序列化器 config.Formatters.Remove(config.Formatters.XmlFormatter);//设置序列化方式为驼峰命名法var jsonFormatter = config.Formatters.OfType<system.net.http.formatting.jsonmediatypeformatter>().First(); jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();// Web API 路由 config.MapHttpAttributeRoutes();//映射路由 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );//将配置注入OWIN管道中 app.UseWebApi(config); }</system.net.http.formatting.jsonmediatypeformatter>
[HttpGet]public HttpResponseMessage GetProduct() {var product = new { id = 1, name = "三星王炸" }; HttpResponseMessage result = new HttpResponseMessage(); result.Content = new StringContent(JsonConvert.SerializeObject(product), Encoding.GetEncoding("UTF-8"), "application/json");return result; }
[HttpGet]public HttpResponseMessage GetProduct2(string id) {var product = new { id = id, name = "三星王炸" }; HttpResponseMessage result = new HttpResponseMessage(); result.Content = new StringContent(JsonConvert.SerializeObject(product), Encoding.GetEncoding("UTF-8"), "application/json");return result; }
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );
以上是讓WebAPI 傳回JSON格式的資料實例教學的詳細內容。更多資訊請關注PHP中文網其他相關文章!