c# 匿名類型獲取值

代碼片斷:json

讀取 new{ ....}對象

 方法1:轉換爲json對象ip

dynamic model = SaleOrderServices.GetGiftOrderById(WebHelper.GetQueryInt("id"));

                var json = JsonConvert.SerializeObject(model);
                var o2 = JsonConvert.DeserializeObject(json) as JObject;
                string CommpanyName = (string)o2["CommpanyName"];
                string STORENAME = (string)o2["STORENAME"];
                string CUSTOMERNAME2jjj = (string)o2["CUSTOMERNAME2"];string

 方法2:若是結果爲空的話,會報錯io

 dynamic expando = new System.Dynamic.ExpandoObject(); //動態類型字段 可讀可寫
                expando.Id = 1;
                expando.Name = "Test";model

  PropertyDescriptorCollection collection = TypeDescriptor.GetProperties(model);
                PropertyDescriptor cnpd = collection.Find("CommpanyName", true);
                ViewData["CommpanyName"] = cnpd != null ? cnpd.GetValue(model).ToString() : "";
                
                PropertyDescriptor cn2pd = collection.Find("CUSTOMERNAME2", true);
                ViewData["CUSTOMERNAME2"] = cn2pd!=null? cn2pd.GetValue(model).ToString():"";

                PropertyDescriptor snpd = collection.Find("STORENAME", true);
                ViewData["STORENAME"] = snpd != null ? snpd.GetValue(model).ToString() : "";方法

相關文章
相關標籤/搜索