C# web api 对象与JSON互转

 

代码如下:

 //JSON格式类
public class ResultModel { public void Error(string msg) { Direction = "0"; Msg = msg; } /// <summary> /// 错误信息 /// </summary> /// <param name="direction">错误编码</param> /// <param name="msg">说明</param> public void Error(string direction,string msg) { Direction = direction; Msg = msg; } public void Succeed() { Direction = "1"; Msg = ""; } public void Succeed(object data) { Direction = "1"; Msg = ""; Data = data; } public string Direction { get; set; } public string Msg { get; set; } public object Data { get; set; } }

 

    public class Convert<T> where T : class
    {
        #region 转换
        /// <summary>
        /// json参数 转对象
        /// </summary>
        /// <param name="json">json参数</param>
        /// <returns></returns>
        public T ToObj(string json)
        {
            T parameter = null;
            try
            {
                //参数为空
                if (string.IsNullOrEmpty(json) || json == "")
                {
                    return null;
                }

                parameter = Activator.CreateInstance<T>();
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
                {
                    DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
                    parameter = (T)dcj.ReadObject(ms);
                }

                if(parameter==null)
                    throw new Exception("参数错误");
            }
            catch (Exception e)
            {
                throw new Exception("参数错误:" + e.Message);
            }

            return parameter;
        }

        /// <summary>/// 
        /// 对象 转 json 
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public string ToJson(T obj)
        {
            string jsonStr;
            if (obj is string || obj is char)
            {
                jsonStr = obj.ToString();
            }
            else
            {
                //对象 转json
                //DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
                //using (MemoryStream stream = new MemoryStream())
                //{
                //    json.WriteObject(stream, obj);
                //    jsonStr = Encoding.UTF8.GetString(stream.ToArray());
                //}
                jsonStr = new JavaScriptSerializer().Serialize(obj);
            }

            //时间格式化
            jsonStr = Regex.Replace(jsonStr, @"\\/Date\((\d+)\)\\/", match =>
            {
                DateTime dt = new DateTime(1970, 1, 1);
                dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
                dt = dt.ToLocalTime();
                return dt.ToString("yyyy-MM-dd HH:mm:ss");
            });

            return jsonStr;
        }
        #endregion


        /// <summary>
        /// 校验
        /// </summary>
        /// <param name="json">参数json</param>
        /// <param name="verifyFiled">要判定的字段</param>
        /// <param name="msg">返回内容</param>
        /// <returns></returns>
        public bool Verify(T parameter, string[] verifyFiled)
        {
            if (parameter == null)
            {
                throw new Exception("参数错误");
            }
            else
            {
                Type t = parameter.GetType();//获得该类的Type
                foreach (string filed in verifyFiled)
                {
                    //查询 当前要判定的属性
                    PropertyInfo pi = t.GetProperties().Where(p => p.Name == filed).FirstOrDefault();
                    if (pi != null)
                    {
                        object value = pi.GetValue(parameter, null);//用pi.GetValue获得值

                        switch (pi.Name)
                        {
                            case "UserId":
                                IsInt(value);
                                break;
                            case "Mobile":
                                IsMobile(value);
                                break;
                            case "CardInfo":
                                IsCardInfo(value);
                                break;
                            default:
                                IsNull(value);
                                break;
                        }
                    }
                }

                return true;
            }
        }

 
        /// <summary>
        /// return httpResponse
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public HttpResponseMessage ToHttpResponse(string val)
        {
            HttpResponseMessage result = new HttpResponseMessage
            {
                Content = new StringContent(val, Encoding.GetEncoding("UTF-8"),
                 "application/json"),
            };

            return result;
        }
    }

 

具体使用代码:

 

 

 public HttpResponseMessage Login([FromBody]string parameter)
        {
ResultModel resultModel = new ResultModel(); Convert
<viewModel> loginConvert = new Convert<viewModel>(); try {
//JSON转成对象
var p = loginConvert.ToObj(parameter); loginConvert.Verify(p, new string[] { "LoginName", "LoginPass" }); //校验参数
//根据转换好的类型查到实例 var viewModel = MyServices.Login(p.LoginName, p.LoginPass);
//转成JSON信息格式 resultModel.Succeed(viewModel); }
catch (Exception e) { resultModel.Error(e.Message); } //转成JSON return resultConvert.ToHttpResponse(resultConvert.ToJson(resultModel)); }

 

转载于:https://www.cnblogs.com/yuanye0918/p/5952707.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值