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 ...
随机推荐
- Cordic 算法入门
三角函数的计算是个复杂的主题,有计算机之前,人们通常通过查找三角函数表来计算任意角度的三角函数的值.这种表格在人们刚刚产生三角函数的概念的时候就已经有了,它们通常是通过从已知值(比如sin(π/2)= ...
- “DNS隧道”盗号木马分析——类似hjack偷密码然后利用dns tunnel直传数据发送出去
摘自:http://www.freebuf.com/articles/network/38276.html# 运行后不断监控顶端窗口,一旦发现为QQ,就弹出一个自己伪造的QQ登陆窗口,诱导用户输入密码 ...
- poj--1149--PIGS(最大流经典建图)
PIGS Time Limit: 1000MS Memory Limit: 10000KB 64bit IO Format: %I64d & %I64u Submit Status D ...
- Python: PS 图层混合算法汇总
本文用 Python 实现了PS 中的图层混合算法,把很多常见的图层混合算法都汇总到了一起,比起以前写的算法,就是用矩阵运算代替了很耗时的for 循环,运行效率有所提升.具体的代码如下: import ...
- sqlserver自定义函数(标量值函数,表值函数)
用户自定义的函数有两类:表值函数.标量值函数. 表值函数:返回值是数据表的函数 调用方式 select b.* from tableA a accross apply Fun_BiaoZhiFun ...
- VirtualBox中Linux虚拟机与主机共享文件夹
VirtualBox中Linux虚拟机与主机共享文件夹 一.Linux虚拟机安装增强功能 二.点击虚拟机 设置-->选择 共享文件夹-->点击右侧的带加号的文件夹图标,执行下面的操作1. ...
- flex 光标(CursorManager)
flex 光标(CursorManager) CursorManager相关属性 getInstance():ICursorManager AIR 应用程序中的每个 mx.core.Window ...
- web开发快速提高工作效率的一些资源
前端学习资源实在是又多又广,在这样的一个知识的海洋里,我们像一块海绵一样吸收,想要快速提高效率,平时的总结不可缺少,以下总结了一些,排版自我感觉良好,推送出来,后续持续跟新中...... 开发工具 H ...
- 【Codeforces Round #425 (Div. 2) B】Petya and Exam
[Link]:http://codeforces.com/contest/832/problem/B [Description] *能代替一个字符串(由坏字母组成); ?能代替单个字符(由好字母组成) ...
- 启动和停止Service
activity_main <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" ...