(转)WebApi返回Json格式字符串
原文地址:https://www.cnblogs.com/elvinle/p/6252065.html
WebApi返回json格式字符串, 在网上能找到好几种方法, 其中有三种普遍的方法, 但是感觉都不怎么好.
先贴一下, 网上给的常用方法吧.
方法一:(改配置法)
找到Global.asax文件,在Application_Start()方法中添加一句:

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;
var result = new HttpResponseMessage{ Content = new StringContent(userName,Encoding.GetEncoding("UTF-8"), "application/json")};
return result;
}
方法二:(万金油法)
方法一中又要改配置,又要处理返回值为String类型的json,甚是麻烦,不如就不用webapi中的的自动序列化对象,自己序列化后再返回

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",解决方法同方法一。
其实WebApi会自动把返回的对象转为xml和json两种格式并存的形式,方法一与方法三是毙掉了xml的返回,而方法二是自定义返回。
以上三种方法, 就是我找到的比较普遍的方法了. 但是总觉得并不是那么好. 都要改这改那的.
还有一种方式能返回json格式字符串. 先看一下效果吧.

public class HomeController : ApiController
{
[HttpGet]
public JsonData Know(string msg)
{
msg = "WebApi 已接收到信息" ;
return new JsonData() { Content = new List<string>() { "a", "b", "c" }, IsSuccess = true, Message = msg };
} public List<string> Get()
{
return new List<string>() { "a", "b", "c"};
}
}



看的出来, Know方法返回的是 json 格式的字符串, Get方法, 返回的是xml格式的.
从上面来看, 主要是返回值不一样. 那么JsonData里面有什么秘密呢?

public class JsonData : ISerializable
{
#region 属性 /// <summary>
/// 表示业务是否正常
/// </summary>
public bool IsSuccess { get; set; } /// <summary>
/// 返回消息,成功的消息和错误消息都在这里
/// </summary>
public string Message { get; set; } /// <summary>
/// 用于返回复杂结果
/// </summary>
public object Content { get; set; }
#endregion #region 方法
/// <summary>
/// 自定义序列化方法
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// 运用info对象来添加你所需要序列化的项
info.AddValue("IsSuccess", IsSuccess);
info.AddValue("Message", Message);
if (Content != null)
{
info.AddValue("Content", Convert.ChangeType(Content, Content.GetType()));
}
else
{
info.AddValue("Content", null);
}
} public JsonData() { }
#endregion
}

这里主要是要实现 ISerializable 接口 .
可能有人注意到, 我访问api的时候, 路由模式和访问mvc是一样的, 其实这里很简单, 只需要在webapi路由注册哪里, 加入一个路由就可以了.
config.Routes.MapHttpRoute(
name: "DefaultApi1",
routeTemplate: "api/{controller}/{action}",
defaults: new { id = RouteParameter.Optional }
);
这样, 就加入了一个路由匹配规则进去. 只不过, 需要在Know方法上面, 加上一些访问限制条件. 如httpget, 否则, 如果直接去访问, 是不可以的.
(转)WebApi返回Json格式字符串的更多相关文章
- WebApi返回Json格式字符串
WebApi返回json格式字符串, 在网上能找到好几种方法, 其中有三种普遍的方法, 但是感觉都不怎么好. 先贴一下, 网上给的常用方法吧. 方法一:(改配置法) 找到Global.asax文件,在 ...
- webapi返回json格式优化
一.设置webapi返回json格式 在App_Start下的WebApiConfig的注册函数Register中添加下面这代码 config.Formatters.Remove(config.For ...
- webapi返回json格式优化 转载https://www.cnblogs.com/GarsonZhang/p/5322747.html
一.设置webapi返回json格式 在App_Start下的WebApiConfig的注册函数Register中添加下面这代码 1 config.Formatters.Remove(config.F ...
- webapi返回json格式,并定义日期解析格式
1.webapi返回json格式 var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferen ...
- WebAPI搭建(二) 让WebAPI 返回JSON格式的数据
在RestFul风格盛行的年代,对接接口大多数人会选择使用JSON,XML和JSON的对比传送(http://blog.csdn.net/liaomin416100569/article/detail ...
- 如何让Asp.net webAPI返回JSON格式数据
ASP.NET Web API 是新一代的 HTTP 網路服務開發框架,除了可以透過 Visual Studio 2012 快速開發外 (內建於 ASP.NET MVC 4 的 Web API 專案範 ...
- 指定webapi 返回 json 格式 ; GlobalConfiguration.Configuration.Formatters.Clear()
因为 Internet Explorer 和 Firefox 发送了不同的 Accept 头,所以 web API 在响应里就发送了不同的内容类型. 解决方法,在 Global.asax的 App ...
- ASP.NET Core WebApi 返回统一格式参数(Json 中 Null 替换为空字符串)
相关博文:ASP.NET Core WebApi 返回统一格式参数 业务场景: 统一返回格式参数中,如果包含 Null 值,调用方会不太好处理,需要替换为空字符串,示例: { "respon ...
- JSon_零基础_001_将布尔类型数组转换为JSon格式字符串,返回给界面
将布尔类型数组转换为JSon格式字符串,返回给界面 需要导入包: 编写bean: package com.west.webcourse.po; /** * 第01步:编写bean类, * 下一步com ...
随机推荐
- spring 自己定义标签 学习二
在上篇中写的仅仅支持写属性,不支持标签property的写法,可是假设有时候我们还想做成支持 property的使用方法,则能够在xsd中添加spring 自带的xsd引用 改动xsd文件例如以下 ...
- JMeter 各组件介绍以及用法
录制脚本 常用组件 参数化 关联
- adb command
- taro 事件处理
https://nervjs.github.io/taro/docs/event.html Taro 元素的事件处理和 DOM 元素的很相似.但是有一点语法上的不同: Taro 事件绑定属性的命名采用 ...
- 关于 TypeReference 的解释
首先 TypeReference 是描述 一个复杂 泛型的工具类. TypeReference 很多类库都有,用 fastjson 的 举例,大概就这个意思. 例子: Response<Fee ...
- spring-配置事务
使用注解方式配置事务: 一.事物管理 事务是一系列的动作,一旦其中有一个动作出现错误,必须全部回滚,系统将事务中对数据库的所有已完成的操作全部撤消,滚回到事务开始的状态,避免出现由于数据不一致而导致的 ...
- git 查看提交历史
查看提交历史 git log 查看每次提交的具体改动内容 git log -p 查看某个文件历次提交的具体改动内容 git log -p <file name> # git log -p ...
- pyhanlp 中文词性标注与分词简介
pyhanlp 中文词性标注与分词简介 pyhanlp实现的分词器有很多,同时pyhanlp获取hanlp中分词器也有两种方式 第一种是直接从封装好的hanlp类中获取,这种获取方式一共可以获取五种分 ...
- 【Spark Java API】broadcast、accumulator
转载自:http://www.jianshu.com/p/082ef79c63c1 broadcast 官方文档描述: Broadcast a read-only variable to the cl ...
- mig_7series DDR控制器的配置
mig_7series DDR控制器的配置