zoukankan      html  css  js  c++  java
  • 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)); }
  • 相关阅读:
    English trip -- VC(情景课)9 A Get ready
    English trip -- Review Unit8 Work 工作
    English trip -- VC(情景课)8 D Reading
    bzoj 4238 电压
    luoguP2154 [SDOI2009]虔诚的墓主人
    bzoj 2225 [Spoj 2371]Another Longest Increasing
    bzoj 4383 [POI2015]Pustynia
    luogu3706 [SDOI2017]硬币游戏
    luogu P6125 [JSOI2009]有趣的游戏
    luogu4443 coci 2017 Dajave
  • 原文地址:https://www.cnblogs.com/yuanye0918/p/5952707.html
Copyright © 2011-2022 走看看