Fork me on GitHub
.net求学者

C#匿名对象(转JSON)互转、动态添加属性

多类型匿名对象

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——有匿名对象(IEnumerable、Linq)有时候不必要每次去创建新的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();

 

//用ExpandoObject 动态添加属性 存储和获取值
        static void Main()
        {
            dynamic expando = new ExpandoObject();
            //{System.Dynamic.ExpandoObject}
            IDictionary<string, object> dictionary = expando;
            //{System.Dynamic.ExpandoObject}
            expando.First = "value set dynamically";
            Console.WriteLine(dictionary["First"]);
 
            dictionary["Second"] = "value set with dictionary";
            Console.WriteLine(expando.Second);
    }

 

 /// <summary>
        /// 获取子节点数据
        /// </summary>
        /// <param name="strUpDicID"></param>
        /// <param name="listData"></param>
        /// <returns></returns>
        private List<dynamic> GetChildren(string strUpDicID, List<T_ExamineDicInfo> listData)
        {
            List<dynamic> listDy = new List<dynamic>();
            var tempList = listData.Where(f => f.UpDicID == strUpDicID);
            if (tempList != null)
            {
                foreach (var item in tempList)
                {
                    string strName ="";

                    var model = new
                    {
                        id = item.DicID,
                        text = strName,
                        state = "open",
                        attributes = new { TotalScore = item.TotalScore, Name = item.DicName },
                        children = GetChildren(item.DicID, listData)
                    };

                    listDy.Add(model);
                }
            }
            return listDy;
        }

 

posted @ 2016-11-21 22:01  hy31337  阅读(5294)  评论(0编辑  收藏  举报
.net求学者