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

2021-06-27 07:07

阅读:429

标签: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();

        /// 
        /// 将一个对象转换成json格式字符串
        /// 
        /// 
        /// 
        /// 
        public static string ToJson(this T t)
        {
            return Serializer.Serialize(t);
        }

        /// 
        /// 把对象转换为JSON字符串
        /// 
        /// 对象
        /// JSON字符串
        public static string ToJSON(this object o)
        {
            if (o == null)
            {
                return null;
            }
            return JsonConvert.SerializeObject(o);
        }
        /// 
        /// 把Json文本转为实体
        /// 
        /// 
        /// 
        /// 
        public static T FromJSON(this string input)
        {
            try
            {
                return JsonConvert.DeserializeObject(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(retString);

            WordResponse wordResponse = JsonTool.FromJSON(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


评论


亲,登录后才可以留言!