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

 

转载于:https://www.cnblogs.com/elves/p/6087186.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值