最近在做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了。