web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返回为json呢,下面就介绍两种方法: 方法一:(改配置法)
找到Global.asax文件,在Application_Start()方法中添加一句:

。 代码如下:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

修改后:

。 代码如下:
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes); // 使api返回为json
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}

这样返回的结果就都是json类型了,但有个不好的地方,如果返回的结果是String类型,如123,返回的json就会变成"123";
解决的方法是自定义返回类型(返回类型为HttpResponseMessage)

。 代码如下:
public HttpResponseMessage PostUserName(User user) { String userName = user.userName;
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(userName,Encoding.GetEncoding("UTF-8"), "application/json") };
return result; }

方法二:(万金油法)
方法一中又要改配置,又要处理返回值为String类型的json,甚是麻烦,不如就不用web api中的的自动序列化对象,自己序列化后再返回

。 代码如下:
public HttpResponseMessage PostUser(User user) { JavaScriptSerializer serializer = new JavaScriptSerializer();
string str = serializer.Serialize(user); HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; return result; }

方法二是我比较推荐的方法,为了不在每个接口中都反复写那几句代码,所以就封装为一个方法这样使用就方便多了。

。 代码如下:
public static HttpResponseMessage toJson(Object obj) { String str; if (obj is String ||obj is Char)
{ str = obj.ToString(); } else { JavaScriptSerializer serializer = new JavaScriptSerializer(); str = serializer.Serialize(obj);
} HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
return result; }

方法三:(最麻烦的方法)
方法一最简单,但杀伤力太大,所有的返回的xml格式都会被毙掉,那么方法三就可以只让api接口中毙掉xml,返回json
先写一个处理返回的类:

。 代码如下:
public class JsonContentNegotiator : IContentNegotiator { private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter) { _jsonFormatter = formatter; }
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) { var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json")); return result; } }

找到App_Start中的WebApiConfig.cs文件,打开找到Register(HttpConfiguration config)方法
添加以下代码:

。 代码如下:
var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

添加后代码如下:

。 代码如下:
public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute(
name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional } ); var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter)); }

方法三如果返回的结果是String类型,如123,返回的json就会变成"123",解决方法同方法一。
其实web api会自动把返回的对象转为xml和json两种格式并存的形式,方法一与方法三是毙掉了xml的返回,而方法二是自定义返回。

web Api 返回json 的两种方式的更多相关文章

  1. MVC web api 返回JSON的几种方式,Newtonsoft.Json序列化日期时间去T的几种方式。

    原文链接:https://www.muhanxue.com/essays/2015/01/8623699.html MVC web api 返回JSON的几种方式 1.在WebApiConfig的Re ...

  2. SpringMVC 返回json的两种方式

    前后台数据交互使用json是一种很重要的方式.本文主要探讨SpringMVC框架使用json传输的技术. 请注意,本文所提到的项目使用Spring 版本是4.1.7,其他版本在具体使用上可能有不一样的 ...

  3. c#操作json的两种方式

    总结一下C#操作json的两种方式,都是将对象和json格式相转. 1.JavaScriptSerializer,继承自System.Web.Script.Serialization private ...

  4. .net mvc web api 返回 json 内容,过滤值为null的属性

    原文:http://blog.csdn.net/xxj_jing/article/details/49508557 版权声明:本文为博主原创文章,未经博主允许不得转载. .net mvc web ap ...

  5. Asp.net Web API 返回Json对象的两种方式

    这两种方式都是以HttpResponseMessage的形式返回, 方式一:以字符串的形式 var content = new StringContent("{\"FileName ...

  6. ASP.NET WEB API 返回JSON 出现2个双引号问题

    前言          在使用ASP.NET WEB API时,我想在某个方法返回JSON格式的数据,于是首先想到的就是手动构建JSON字符串,如:"{\"result\" ...

  7. easyUI之datagrid绑定后端返回数据的两种方式

    先来看一下某一位大佬留下的easyUI的API对datagrid绑定数据的两种方式的介绍. 虽然精简,但是,很具有“师傅领进门,修行靠个人”的精神,先发自内心的赞一个. 但是,很多人和小编一样,第一次 ...

  8. 获取Executor提交的并发执行的任务返回结果的两种方式/ExecutorCompletionService使用

    当我们通过Executor提交一组并发执行的任务,并且希望在每一个任务完成后能立即得到结果,有两种方式可以采取: 方式一: 通过一个list来保存一组future,然后在循环中轮训这组future,直 ...

  9. Java中将xml文件转化为json的两种方式

    原文地址https://blog.csdn.net/a532672728/article/details/76312475 最近有个需求,要将xml转json之后存储在redis中,找来找去发现整体来 ...

随机推荐

  1. JDK1.5/1.6/1.7之新特性总结(转载)

    原文地址:http://www.cnblogs.com/yezhenhan/archive/2011/08/16/2141510.html 如果原作者看到不想让我转载请私信我! 开发过程中接触到了从j ...

  2. wpf——三维学习1

    以下xmal是我从msdn上复制下来的.是用于在wpf中创建3d模型的实例链接https://msdn.microsoft.com/zh-cn/library/ms747437.aspx看它的使用方式 ...

  3. LINQ

    lambda表达式: LINQ to Object: 参考:http://www.cnblogs.com/leon-y-liu/articles/3575009.html LINQ to XML: u ...

  4. Mysql InnoDB 共享表空间和独立表空间

    前言:学习mysql的时候总是习惯性的和oracle数据库进行比较.在学习mysql InnoDB的存储结构的时候也免不了跟oracle进行比较.Oracle的数据存储有表空间.段.区.块.数据文件: ...

  5. Win10 UI动画

    <Button Content="Ship via Wells, Fargo & Co." HorizontalAlignment="Center" ...

  6. [leetcode] 数字游戏

    169. Majority Element Given an array of size n, find the majority element. The majority element is t ...

  7. form表单提交问题

    1.提交后不能跳转到指定页面 jsp代码 <form class="form-horizontal" role="form"> <p clas ...

  8. C#区分多态和重载-delphi也类似

    Delphi也是基于继承和接口的多态性.

  9. ajax删除DB数据

    1.前台js $().ready(function () { $('[name="checkAll"]').click(function () { if ("checke ...

  10. Code Complete 笔记—— 第一章

    软件的构建的主要流程: 定义问题 ( Problem Definition) 需求分析 (Requirements Development) 规划构建 (construction planning) ...