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

        /// <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);

猜你喜欢

转载自www.cnblogs.com/chengulv/p/9610171.html
今日推荐