1、调用webapi接口时,碰到一种情况:
通过webapi调用接口时,返回的json数据,死活转换不成对象,转换的对象一直为null;
webapi端代码:
[HttpGet] public string GetResponse() { WordResponse response = new WordResponse(); response.Result = false; response.PageNum = 12; return JsonHelper.ToJson(response); }
public static class JsonHelper { static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer(); /// <summary> /// 将一个对象转换成json格式字符串 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns></returns> public static string ToJson<T>(this T t) { return Serializer.Serialize(t); } /// <summary> /// 把对象转换为JSON字符串 /// </summary> /// <param name="o">对象</param> /// <returns>JSON字符串</returns> public static string ToJSON(this object o) { if (o == null) { return null; } return JsonConvert.SerializeObject(o); } /// <summary> /// 把Json文本转为实体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="input"></param> /// <returns></returns> public static T FromJSON<T>(this string input) { try { return JsonConvert.DeserializeObject<T>(input); } catch (Exception ex) { return default(T); } } }
接收端代码:
string serviceAddress = string.Format("http://192.168.168.152:9094/api/Word/GetResponse"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress); request.Method = "GET"; request.ContentType = "application/json;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); new SysLogInfoService().SysErrorLog("报告页数", "报告页数", retString); WordResponse wordResponse1 = JsonHelper.ToObject<WordResponse>(retString); WordResponse wordResponse = JsonTool.FromJSON<WordResponse>(retString);
最后发现,通过api返回json数据时,不要再转换为json,否则返回的json中会多一些斜线/,导致转换为对象失败,所以对象为空。
所以讲webapi接口代码改为:
[HttpGet] public WordResponse GetResponse() { WordResponse response = new WordResponse(); response.Result = false; response.PageNum = 12; return response; }
原因是,webapi接口,内置的已经会将返回的接口转换为json传输,并不需要自行转json,转完的对象相当于会再多一层引号,导致解析对象失败。