码迷,mamicode.com
首页 > Windows程序 > 详细

.net web api应用遇到的一些问题

时间:2018-12-07 20:56:27      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:java   ade   coding   new   api   rip   char   ret   .net   

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中会多一些斜线/,导致转换为对象失败,所以对象为空。

.net web api应用遇到的一些问题

标签:java   ade   coding   new   api   rip   char   ret   .net   

原文地址:https://www.cnblogs.com/wanggang2016/p/10084334.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!