silverlight依据json字符串动态创建实体类
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;
}
}
silverlight依据json字符串动态创建实体类的更多相关文章
- c# 利用反射 从json字符串 动态创建类的实例 并动态为实例成员赋值
转自 http://hi.baidu.com/wjinbd/item/c54d43d998beb33be3108fdd 1 创建自己要用的类 class stu { string _name; int ...
- 由json字符串生成C#实体类的工具
json作为互联网上轻量便捷的数据传输格式,越来越受到重视.但在服务器端编程过程中,我们常常希望能通过智能提示来提高编码效率.JSON C# Class Generator 能将json格式所表示的J ...
- JSON C# Class Generator ---由json字符串生成C#实体类的工具(转)
转载地址:http://www.cnblogs.com/finesite/archive/2011/07/31/2122984.html json作为互联网上轻量便捷的数据传输格式,越来越受到重视.但 ...
- JSON C# Class Generator ---由json字符串生成C#实体类的工具
json作为互联网上轻量便捷的数据传输格式,越来越受到重视.但在服务器端编程过程中,我们常常希望能通过智能提示来提高编码效率.JSON C# Class Generator 能将json格式所表示的J ...
- json字符串生成C#实体类的工具
转载:http://www.cnblogs.com/finesite/archive/2011/07/31/2122984.html json作为互联网上轻量便捷的数据传输格式,越来越受到重视.但在服 ...
- JSON字符串转C#实体Class类
在项目开发过程中,经常需要和不同部门或者不同的组员一起协同工作,但对方写的json返回的结果集,我们需要用,那么如何来生成对应的类代码和实体对象呢?于是参考了网上的做法,做一个简单的字符串转实体类的功 ...
- 初探原生js根据json数据动态创建table
初探原生js根据json数据动态创建table 小生以实习生的职位进入了一家非纯软件的公司做asp.net开发,大半个月下来发现公司里居然没有前端工程师,这令我很诧异,跟着公司做项目,发现前端后台没有 ...
- 使用MyBatis的Generator自动创建实体类和dao的接口与xml
在实际的项目中其实建立数据库和设计数据库的时候特别重要,而等数据库设计完成之后,根据数据库创建实体类的工作就特别麻烦和繁琐了,不仅很麻烦,而且很浪费时间,不做又不行,这次就找到了一个简单的方法可以让m ...
- .NET Core、EF、Dapper、MySQL 多种方式实现数据库操作(动态注册实体类)
目录 前言 一.技术选型 二.遇到的坑 2.1..NET Core 下 EF 的问题 2.2.数据库实体类的注册 切记坑 前言 最近在学习.研究 .NET Core 方面的知识,动手搭建了一些小的 D ...
随机推荐
- 启动springboot
新建一个springboot项目,idea的做法:一般直接next就行 填写项目使用到的技术,上面的Spring Boot版本建议选择最新的稳定版,主要勾选上Web就可以了,如下图: 新建之后< ...
- 初识activiti
Activity工作流学习要点 1. 1个插件 在Eclipse中安装Activity插件,让你可以在Eclipse中绘制Activity工作流图 2. 1个引擎 ProcessEngine对象,Ac ...
- node --- 服务一直启动
使用node xxx.js命令可以开始在服务器运行node.js程序. 可是它会占用终端的当前进程,而且当你离开服务器连接的时候(e.g.关闭终端或者Putty) node.js程序也会退出. 如何让 ...
- BZOJ 3544 treap (set)
我只是想找个treap的练习题-- 每回找到lower_bound 就好啦 //By SiriusRen #include <cstdio> #include <cstring> ...
- jQuery - 设置内容和属性 设置内容 - text()、html() 以及 val() , 设置属性 - attr()
jQuery - 设置内容和属性 设置内容 - text().html() 以及 val() text() - 设置或返回所选元素的文本内容 html() - 设置或返回所选元素的内容(包括 HTM ...
- Linux常用PDF阅读软件
1.福昕阅读器是一款PDF文档阅读器,对中文的支持度非常高.福昕阅读器作为全球最流行的PDF阅读器,能够快速打开.浏览.审阅.注释.签署及打印任何PDF文件. 2.evince是一个支持多种格式的文件 ...
- ES6学习笔记(五)函数的扩展
1.函数参数的默认值 1.1基本用法 ES6 之前,不能直接为函数的参数指定默认值,只能采用变通的方法. function log(x, y) { y = y || 'World'; console. ...
- VUE里子组件获取父组件动态变化的值
在VUE里父组件给子组件间使用props方式传递数据,但是希望父组件的一个状态值改变然后子组件也能监听到这个数据的改变来更新子组件的状态. 场景:子组件通过props获取父组件传过来的数据,子组件存在 ...
- XCode6报数组越界错误的问题
今天碰到一个非常奇葩的问题, 调试了半天: 错误:"index 0 beyond bounds for empty array", 意思就是说数据源数组为nil, 所以你调用直接 ...
- NYOJ 203 三国志(Dijkstra+贪心)
三国志 时间限制:3000 ms | 内存限制:65535 KB 难度:5 描写叙述 <三国志>是一款非常经典的经营策略类游戏.我们的小白同学是这款游戏的忠实玩家.如今他把游戏简化一下 ...