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);

silverlight依据json字符串动态创建实体类的更多相关文章

  1. c# 利用反射 从json字符串 动态创建类的实例 并动态为实例成员赋值

    转自 http://hi.baidu.com/wjinbd/item/c54d43d998beb33be3108fdd 1 创建自己要用的类 class stu { string _name; int ...

  2. 由json字符串生成C#实体类的工具

    json作为互联网上轻量便捷的数据传输格式,越来越受到重视.但在服务器端编程过程中,我们常常希望能通过智能提示来提高编码效率.JSON C# Class Generator 能将json格式所表示的J ...

  3. JSON C# Class Generator ---由json字符串生成C#实体类的工具(转)

    转载地址:http://www.cnblogs.com/finesite/archive/2011/07/31/2122984.html json作为互联网上轻量便捷的数据传输格式,越来越受到重视.但 ...

  4. JSON C# Class Generator ---由json字符串生成C#实体类的工具

    json作为互联网上轻量便捷的数据传输格式,越来越受到重视.但在服务器端编程过程中,我们常常希望能通过智能提示来提高编码效率.JSON C# Class Generator 能将json格式所表示的J ...

  5. json字符串生成C#实体类的工具

    转载:http://www.cnblogs.com/finesite/archive/2011/07/31/2122984.html json作为互联网上轻量便捷的数据传输格式,越来越受到重视.但在服 ...

  6. JSON字符串转C#实体Class类

    在项目开发过程中,经常需要和不同部门或者不同的组员一起协同工作,但对方写的json返回的结果集,我们需要用,那么如何来生成对应的类代码和实体对象呢?于是参考了网上的做法,做一个简单的字符串转实体类的功 ...

  7. 初探原生js根据json数据动态创建table

    初探原生js根据json数据动态创建table 小生以实习生的职位进入了一家非纯软件的公司做asp.net开发,大半个月下来发现公司里居然没有前端工程师,这令我很诧异,跟着公司做项目,发现前端后台没有 ...

  8. 使用MyBatis的Generator自动创建实体类和dao的接口与xml

    在实际的项目中其实建立数据库和设计数据库的时候特别重要,而等数据库设计完成之后,根据数据库创建实体类的工作就特别麻烦和繁琐了,不仅很麻烦,而且很浪费时间,不做又不行,这次就找到了一个简单的方法可以让m ...

  9. .NET Core、EF、Dapper、MySQL 多种方式实现数据库操作(动态注册实体类)

    目录 前言 一.技术选型 二.遇到的坑 2.1..NET Core 下 EF 的问题 2.2.数据库实体类的注册 切记坑 前言 最近在学习.研究 .NET Core 方面的知识,动手搭建了一些小的 D ...

随机推荐

  1. .Net 跳转

    Action正常跳转 <a href="@Url.Action("AppDownload")">点击下载APP</a> public A ...

  2. bind DNS搭建笔记

    设置默认网关 偶尔会出现问题 route add default gw 192.168.0.1 .vim /etc/sysctl.conf 这里是重点 配置路由转发,路由开启等都要用到. # Cont ...

  3. 线程框架Executor的用法举例

    java5线程框架Executor的用法举例 Executor 是 java5 下的一个多任务并发执行框架(Doug Lea),可以建立一个类似数据库连接池的线程池来执行任务.这个框架主要由三个接口和 ...

  4. 学习NLP:《精通Python自然语言处理》中文PDF+英文PDF+代码

    自然语言处理是计算语言学和人工智能之中与人机交互相关的领域之一. 推荐学习自然语言处理的一本综合学习指南<精通Python自然语言处理>,介绍了如何用Python实现各种NLP任务,以帮助 ...

  5. 学习TF:《TensorFlow技术解析与实战》PDF+代码

    TensorFlow 是谷歌公司开发的深度学习框架,也是目前深度学习的主流框架之一.<TensorFlow技术解析与实战>从深度学习的基础讲起,深入TensorFlow框架原理.模型构建. ...

  6. PHP解析XML格式文档

    <?php// 首先要建一个DOMDocument对象$xml = new DOMDocument();// 加载Xml文件$xml->load("3.xml");// ...

  7. SQL脚本存在TABLE ACCESS FULL行为

    对于SQL的执行计划,一般尽量避免TABLE ACCESS FULL的出现,那怎样去定位,系统里面哪些SQL脚本存在TABLE ACCESS FULL行为,对于9i及以后版本,使用以下语句即可 sel ...

  8. 【v2.x OGE教程 12】 关卡编辑器帮助文档

    ] 关卡编辑器帮助文档 一.简单介绍 关卡编辑器用于游戏关卡界面元素的可视化编辑,包含元素的位置.尺寸以及其他自己定义属性.通过解析生成的数据文件就可以获取关卡信息,并能随时调整.以降低开发工作量,提 ...

  9. Android学习笔记(23):列表项的容器—AdapterView的子类们

    AdapterView的子类的子类ListView.GridView.Spinner.Gallery.AdapterViewFlipper和StackView都是作为容器使用,Adapter负责提供各 ...

  10. JavaScript定时调用函数(SetInterval与setTimeout)

    setTimeout和setInterval的语法同样.它们都有两个參数.一个是将要运行的代码字符串.另一个是以毫秒为单位的时间间隔,当过了那个时间段之后就将运行那段代码. 只是这两个函数还是有差别的 ...