多類型匿名對象
var result = new { pages = 10, users = new System.Collections.ArrayList { new{id=1,name="2"}, new{id=2,name="3"} } }; result.users.Add(new { id = 3, name = "4" }); new { a = Tuple .Create( new List<Attribute>() { new MaskAttribute(".00") },1), b = Tuple .Create( new List<Attribute>() { new MaskAttribute("#.0") },2) } public static Tuple<List<attributes>,T> CreateMetaField <T>(this T value , params Attribute[] args) new { a=1.CreateMetaField(new attr...() ) , b=2.CreateMetaField(new attr...() ) }
完全動態方式2:
public class DynamicClassHelper { /// <summary> /// 創建屬性 /// </summary> /// <param name="propertyname"></param> /// <returns></returns> private static string Propertystring(string propertyname) { StringBuilder sbproperty = new StringBuilder(); sbproperty.Append(" private string _" + propertyname + " = null;\n"); sbproperty.Append(" public string " + "" + propertyname + "\n"); sbproperty.Append(" {\n"); sbproperty.Append(" get{ return _" + propertyname + ";} \n"); sbproperty.Append(" set{ _" + propertyname + " = value; }\n"); sbproperty.Append(" }"); return sbproperty.ToString(); } /// <summary> /// 創建動態類 /// </summary> /// <param name="listMnProject">屬性列表</param> /// <returns></returns> public static Assembly Newassembly(List<string> propertyList) { //創建編譯器實例。 CSharpCodeProvider provider = new CSharpCodeProvider(); //設置編譯參數。 CompilerParameters paras = new CompilerParameters(); paras.GenerateExecutable = false; paras.GenerateInMemory = true; //創建動態代碼。 StringBuilder classsource = new StringBuilder(); classsource.Append("public class dynamicclass \n"); classsource.Append("{\n"); //創建屬性。 for (int i = 0; i < propertyList.Count; i++) { classsource.Append(Propertystring(propertyList[i])); } classsource.Append("}"); System.Diagnostics.Debug.WriteLine(classsource.ToString()); //編譯代碼。 CompilerResults result = provider.CompileAssemblyFromSource(paras, classsource.ToString()); //獲取編譯后的程序集。 Assembly assembly = result.CompiledAssembly; return assembly; } /// <summary> /// 給屬性賦值 /// </summary> /// <param name="objclass"></param> /// <param name="propertyname"></param> /// <param name="value"></param> public static void Reflectionsetproperty(object objclass, string propertyname, string value) { PropertyInfo[] infos = objclass.GetType().GetProperties(); foreach (PropertyInfo info in infos) { if (info.Name == propertyname && info.CanWrite) { info.SetValue(objclass, value, null); } } } /// <summary> /// 得到屬性值 /// </summary> /// <param name="objclass"></param> /// <param name="propertyname"></param> public static void Reflectiongetproperty(object objclass, string propertyname) { PropertyInfo[] infos = objclass.GetType().GetProperties(); foreach (PropertyInfo info in infos) { if (info.Name == propertyname && info.CanRead) { System.Console.WriteLine(info.GetValue(objclass, null)); } } } }
使用方法
//將配置的參數名加入propertyList列表 List<string> propertyList = ParamsList.Select(t => t.CodeID).ToList(); //獲取數據導入記錄明細的屬性名 T_DataDetailExtInfo modelDataDetail = new T_DataDetailExtInfo(); Type typeDataDetail = modelDataDetail.GetType(); //獲得該類的Type //將數據表屬性名加入propertyList列表 propertyList.AddRange(typeDataDetail.GetProperties().Select(p => p.Name)); //創建動態類,監測參數ID為它的屬性 Assembly assembly = DynamicClassHelper.Newassembly(propertyList); var listclass = new List<dynamic>(); if (listDataDetail != null && listDataDetail.Count > 0) { //明細數據 foreach (var data in listDataDetail) { dynamic model = assembly.CreateInstance("dynamicclass"); //賦值 DynamicClassHelper.Reflectionsetproperty(model, "ID", data.DetailID); } listclass.Add(model); }
匿名對象轉Json——有匿名對象有時候不必要每次去創建新的Model類或動態創建Model類
List<dynamic> listData = new List<dynamic>(); foreach (var temp in listLog) { var logModel = new { DataDate = temp.DataTime, Content = temp.LogContent }; listData.Add(logModel); } string strJson = JsonHelper.GetUnknownJson(listData); /// <summary> /// 對未知或匿名對象進行Json序列化 ——JsonHelper類 /// </summary> /// <param name="value"></param> /// <returns></returns> public static string GetUnknownJson(object value) { if (value == null) return null; var jss = new JavaScriptSerializer(); jss.MaxJsonLength = int.MaxValue; return jss.Serialize(value); }
JSON轉匿名對象--引用Newtonsoft.Json.dll
//Json轉匿名對象{“code”:“0”,“message”:“success”} var rspObj = JsonConvert.DeserializeAnonymousType(text, new { code = "", message = "" }); //Json轉List的匿名對象 {{“Code”:“V1”,“Text”:“字典1”},{“Code”:“L2”,“Text”:“字典2”},{“Code”:“L3”,“Text”:“字典3”}] var rspObj = JsonConvert.DeserializeAnonymousType(rsp,new[] { new { Code = "", Text = "" } }.ToList());
JObject 使用 -- Newtonsoft.Json
//創建匿名對象 JObject obj = new JObject(); obj.Add("ID", 1); obj.Add("Name", "張三"); obj.Add("Birthday", DateTime.Parse("2000-01-02")); obj.Add("IsVIP", true); obj.Add("Account", 12.34f); // 創建數組 JArray array = new JArray(); array.Add(new JValue("吃飯")); array.Add(new JValue("睡覺")); obj.Add("Favorites", array); obj.Add("Remark", null); // 創建數組2 JArray array = new JArray("吃飯", "睡覺"); //從 Json 字符串創建 JObject string json = "{\"ID\":1,\"Name\":\"張三\",\"Birthday\":\"2000-01-02T00:00:00\",\"IsVIP\":true,\"Account\":12.34,\"Favorites\":[\"吃飯\",\"睡覺\"],\"Remark\":null}"; JObject obj = JObject.Parse(json); //用匿名對象創建 JObject JObject obj = JObject.FromObject(new { name = "jack", age = 18 }); //顯示 { "name": "jack", "age": 18 } //用初始化器 JObject obj = new JObject() { { "name", "jack" }, { "age", 18 } }; //獲取值 int id; if (obj["ID"] != null) id = obj["ID"].Value<int>(); //獲取數組 string[] favorites; if (obj["Favorites"] != null) favorites = obj["Favorites"].Value<List<string>>().ToArray();
//基於創建的list使用LINQ to JSON創建期望格式的JSON數據 lbMsg.InnerText = new JObject( new JProperty("total", studentList.Count), new JProperty("rows", new JArray( //使用LINQ to JSON可直接在select語句中生成JSON數據對象,無須其它轉換過程 from p in studentList select new JObject( new JProperty("studentID", p.StudentID), new JProperty("name", p.Name), new JProperty("homeTown", p.Hometown) ) ) ) ).ToString();