1. 程式人生 > >將Json數據 填充到 實例類 的函數

將Json數據 填充到 實例類 的函數

instance class bool etime oid 實例 mem time bject

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

將Json數據 填充到 實例類 的函數