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
  • 相关阅读:
    nginx的优化
    apache日志轮询技术
    PV IP UV的概念介绍
    日志文件记录的重要性
    linux chmod 755
    ssh免密码登录机器(使用公钥和秘钥进行加密来实现)
    ffmpeg基础
    linux使用grep和find查找内容
    为什么我们会越来越穷?
    从我干程序员开始 我就不准备干这个行业
  • 原文地址:https://www.cnblogs.com/softcg/p/6510928.html
Copyright © 2011-2022 走看看