WebApi和Andriod對接訪問模式問題


最近在做WebApi和Andriod接口的對接,中途出現一個問題就是返回格式的問題。由於之前使用WebService的時候使用的一直都是json的序列化和反序列話格式,所以一開始在webapi中通樣使用格式,但結果卻是Andriod那端始終獲取不到正確的json格式數據,經過大量的資料查詢之后才發現問題,那就是Webapi和webservice的不同之處,webapi默認的返回數據格式是xml的格式,所以Andriod的那段是獲取不到正確的json格式數據的,那我們應該怎樣才能獲取到正確的數據格式呢?其實很簡單,下面我貼出一段代碼:

 [HttpGet]
        public HttpResponseMessage GetMessageInfo(string requestData)
        {
            try
            {
 
               string s= "{\"code\":\"1\",\"messge\":\"成功\"}";
               HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(s, Encoding.GetEncoding("UTF-8"), "application/json") };
               return result;
            }
            catch (Exception ex)
            {
                string s = "{\"code\":\"0\",\"messge\":\"失敗," + ex.Message + "\"}";
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(s, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
        }

  很簡單,把原有的直接json序列化格式換成HttpResponseMessage的返回方式就Ok了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM