关闭

silverlight根据json字符串动态创建实体类

标签: silverlightjson动态创建
1500人阅读 评论(0) 收藏 举报
分类:

1、接收json字符串:

//用JsonValue转换json字符串是为了之后获得json字符串的每行数据和每一列的列名

JsonValue jv = JsonValue.Parse(json);     //JsonValue引用自System.Json

2、创建两个类:一个为创建实体类方法,一个为调用实体类方法,实现操作并返回数据:

//创建实体方法类  

public class DynamicTypeBuilder

    {

        TypeBuilder tb;

        /// <summary>

        /// 构造函数

        /// </summary>

        /// <param name="typeNm">动态类型的名称</param>

        public DynamicTypeBuilder(string typeNm)

        {

            // 在 Silverlight 中 AssemblyBuilderAccess 没有 RunAndSave

            AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(

                new AssemblyName("TempAssembly"), AssemblyBuilderAccess.Run);

            ModuleBuilder mb = ab.DefineDynamicModule("TempModule");

            this.tb = mb.DefineType(typeNm, TypeAttributes.Public);

        }

        /// <summary>

        /// 添加一个public的可读写属性,并且会创建对应的名为 propertyNm + "Field" 的私有字段

        /// </summary>

        /// <param name="propertyNm"></param>

        /// <param name="type"></param>

        public void AppendPublicProperty(string propertyNm, Type type)

        {

            this.AppendPublicProperty(propertyNm, type, true, true);

        }

        /// <summary>

        /// 添加一个public属性,并且会创建对应的名为 propertyNm + "Field" 的私有字段

        /// </summary>

        /// <param name="propertyNm"></param>

        /// <param name="type"></param>

        /// <param name="canGet">是否实现getter</param>

        /// <param name="canSet">是否实现setter</param>

        public void AppendPublicProperty(string propertyNm, Type type, bool canGet, bool canSet)

        {

            string arr = string.Format("{0}Field", propertyNm);

            //FieldBuilder field = this.tb.DefineField(propertyNm, typeof(System.String), FieldAttributes.Private);

            //FieldBuilder field = this.tb.DefineField(arr, type, FieldAttributes.Private);

            FieldBuilder field = tb.DefineField("myField", typeof(System.String), FieldAttributes.Private);

            PropertyBuilder property = tb.DefineProperty(propertyNm, PropertyAttributes.HasDefault, type, null);

            MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;

            if (canGet)

            {

                MethodBuilder getAccessor = tb.DefineMethod(string.Format("get_{0}", propertyNm), getSetAttr, type, Type.EmptyTypes);

                ILGenerator getIL = getAccessor.GetILGenerator();

                // For an instance property, argument default is the instance. Load the

                // instance, then load the private field and return, leaving the

                // field value on the stack.

                getIL.Emit(OpCodes.Ldarg_0);

                getIL.Emit(OpCodes.Ldfld, field);

                getIL.Emit(OpCodes.Ret);

                property.SetGetMethod(getAccessor);

            }

            if (canSet)

            {

                MethodBuilder setAccessor = tb.DefineMethod(string.Format("set_{0}", propertyNm), getSetAttr, null, new Type[] { type });

                setAccessor.DefineParameter(1, ParameterAttributes.None, "value");

                ILGenerator setIL = setAccessor.GetILGenerator();

                // Load the instance and then the numeric argument, then store the

                // argument in the field.

                setIL.Emit(OpCodes.Ldarg_0);

                setIL.Emit(OpCodes.Ldarg_1);

                setIL.Emit(OpCodes.Stfld, field);

                setIL.Emit(OpCodes.Ret);

                property.SetSetMethod(setAccessor);

            }

        }

        /// <summary>

        /// 在添加完各个 public 属性之后,调用此方法以完成对动态类型的定义并加载之,

        /// 此后通过 Activator.CreateInstance() 便可实例化动态类型

        /// </summary>

        /// <returns></returns>

        public Type CreateDynamicType()

        {

            return this.tb.CreateType();

        }

        public Type DynamicCreateType()

        {

            //动态创建程序集

            AssemblyName DemoName = new AssemblyName("DynamicAssembly");

            AssemblyBuilder dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(DemoName, AssemblyBuilderAccess.Run);

            //动态创建模块

            ModuleBuilder mb = dynamicAssembly.DefineDynamicModule("TempModule");

            //动态创建类MyClass

            TypeBuilder tb = mb.DefineType("MyClass", TypeAttributes.Public);

            //动态创建字段

            FieldBuilder fb = tb.DefineField("myField", typeof(System.String), FieldAttributes.Private);

            //动态创建构造函数

            Type[] clorType = new Type[] { typeof(System.String) };

            ConstructorBuilder cb1 = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, clorType);

            //生成指令

            ILGenerator ilg = cb1.GetILGenerator();//生成 Microsoft 中间语言 (MSIL) 指令

            ilg.Emit(OpCodes.Ldarg_0);

            ilg.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes));

            ilg.Emit(OpCodes.Ldarg_0);

            ilg.Emit(OpCodes.Ldarg_1);

            ilg.Emit(OpCodes.Stfld, fb);

            ilg.Emit(OpCodes.Ret);

            //动态创建属性

            PropertyBuilder pb = tb.DefineProperty("MyProperty", PropertyAttributes.HasDefault, typeof(string), null);

            //动态创建方法

            MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName;

            MethodBuilder myMethod = tb.DefineMethod("get_Field", getSetAttr, typeof(string), Type.EmptyTypes);

            //生成指令

            ILGenerator numberGetIL = myMethod.GetILGenerator();

            numberGetIL.Emit(OpCodes.Ldarg_0);

            numberGetIL.Emit(OpCodes.Ldfld, fb);

            numberGetIL.Emit(OpCodes.Ret);

            //使用动态类创建类型

            Type classType = tb.CreateType();

            //保存动态创建的程序集 (程序集将保存在程序目录下调试时就在Debug下)

            //dynamicAssembly.Save(DemoName.Name + ".dll");

            //创建类

            return classType;

        }
//操作实体类
 
public class CreateModel
    {
        public List<Object> GetList(JsonValue colInfos)
        {
            //构造绑定DataGrid ItemSource的集合
            List<Object> list = new List<object>();
            DynamicTypeBuilder dyClass = new DynamicTypeBuilder("dy");//创建动态类,dy可以随便替换
            ////ColInfos为已经取到的列信息集合
            foreach (JsonValue v in colInfos)
            {
                //获取所有列名
                ICollection<string> col = (((System.Json.JsonObject)(v))).Keys;
                foreach (string columnName in col)
                {
                    dyClass.AppendPublicProperty(columnName, typeof(string));
                }
            }
            Type dyType = dyClass.CreateDynamicType();//创建自定义类
            foreach (JsonValue v in colInfos)//循环行
            {
                ICollection<string> col = ((System.Json.JsonObject)(v)).Keys;
                JsonObject row = (System.Json.JsonObject)(v);
                var po = Activator.CreateInstance(dyType);//创建自定义类实例
                foreach (var columnName in row)//循环列
                {//col
                    PropertyInfo property = dyType.GetProperty(columnName.Key);
                    if (columnName.Value == null)
                        property.SetValue(po, "", null);
                    else
                        property.SetValue(po, columnName.Value.ToString().Replace("\"", ""), null);
                }
                list.Add(po);
            }
            return list;
        }
    }
3、根据第一步创建的JsonValue 对象调用操作实体类:
                CreateModel create = new CreateModel();
                JsonValue jv = JsonValue.Parse(json);
                List<Object> li = create.GetList(jv);

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:53733次
    • 积分:843
    • 等级:
    • 排名:千里之外
    • 原创:32篇
    • 转载:2篇
    • 译文:1篇
    • 评论:0条