博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

将Json数据 填充到 实例类 的函数

Posted on 2018-09-08 19:36  快乐家++  阅读(465)  评论(0编辑  收藏  举报
        /// <summary>
        /// 将Json数据 填充到 实例类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="J">json数据</param>
        /// <param name="M">实例类型引用</param>
        public void toInstance<T>(JObject J, ref T M)
        {
            var t = M.GetType();
            foreach (var pi in M.GetType().GetProperties())
            {
                var V = J[pi.Name];
                if (V == null) continue;
                switch (pi.PropertyType.Name)
                {
                    case "Boolean": pi.SetValue(M, V.Value<bool>(), null); break;
                    case "String": pi.SetValue(M, V.Value<string>(), null); break;
                    case "Decimal": pi.SetValue(M, V.Value<Decimal>(), null); break;
                    case "DateTime": pi.SetValue(M, V.Value<DateTime>(), null); break;
                    case "Int16": pi.SetValue(M, V.Value<Int16>(), null); break;
                    case "Int32": pi.SetValue(M, V.Value<int>(), null); break;
                    case "Int64": pi.SetValue(M, V.Value<Int64>(), null); break;
                    case "Single": pi.SetValue(M, V.Value<Single>(), null); break;
                    case "String[]": pi.SetValue(M, V.Select(s => s.Value<string>()).ToArray(), null); break;
                    case "Int32[]": pi.SetValue(M, V.Select(s => s.Value<int>()).ToArray(), null); break;
                }
            }
        }

var J = JsonConvert.DeserializeObject(textBox1.Text) as JObject;

var M = new schemeModel();

toInstance(J, ref M);