zoukankan      html  css  js  c++  java
  • WebApi返回Json

    web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返回为json呢,下面就介绍两种方法: 

    方法一:改配置
    找到Global.asax文件,在Application_Start()方法中添加一句: 
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();  
    方法二:手动序列化
    如:
    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));  
    方法三如果返回的结果是String类型,如123,返回的json就会变成"123",解决方法同方法一。 

    其实web api会自动把返回的对象转为xml和json两种格式并存的形式,方法一与方法三是毙掉了xml的返回,而方法二是自定义返回。 

    QQ:83199235
  • 相关阅读:
    关于p标签
    用unescape反编码得出汉字
    一个未知高度垂直居中的简单方法
    发现个div float的小秘密
    w3cschool关于list-style-position时的另外发现
    oracle 11gR2默认密码修改
    程序员的十楼层。看看自己在第几层
    Steve Yegge:Google面试秘籍
    为学Linux,我看了这些书
    程序员的困境
  • 原文地址:https://www.cnblogs.com/softcg/p/6510928.html
Copyright © 2011-2022 走看看