自定义实现Json字符串向C#对象的转变
来源:互联网 发布:魅族手淘宝网的价格 编辑:程序博客网 时间:2024/05/01 09:58
这里使用Atrribute的方式实现了Json字符串向C#对象的转变。因为功能局限,此版本只是针对于Json字符串,如"response":"Hello","id":21231513,"result":100,"msg":"OK."; 而不是Json数组。这里的Atrribute是作用在属性上,像NHibernate中的Atrribute一样,是在运行时通过反射来获取这个属性对应于Json字符串中的哪个key.
- namespace JsonMapper
- {
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
- public class JsonFieldAttribute : Attribute
- {
- private string _Name = string.Empty;
- public string Name
- {
- get { return _Name; }
- set { _Name = value; }
- }
- }
- }
- namespace JsonMapper
- {
- public class JsonToInstance
- {
- public T ToInstance<T>(string json) where T : new()
- {
- Dictionary<string, string> dic = new Dictionary<string, string>();
- string[] fields = json.Split(',');
- for (int i = 0; i < fields.Length; i++ )
- {
- string[] keyvalue = fields[i].Split(':');
- dic.Add(Filter(keyvalue[0]), Filter(keyvalue[1]));
- }
- PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
- T entity = new T();
- foreach (PropertyInfo property in properties)
- {
- object[] propertyAttrs = property.GetCustomAttributes(false);
- for (int i = 0; i < propertyAttrs.Length; i++)
- {
- object propertyAttr = propertyAttrs[i];
- if (propertyAttr is JsonFieldAttribute)
- {
- JsonFieldAttribute jsonFieldAttribute = propertyAttr as JsonFieldAttribute;
- foreach (KeyValuePair<string ,string> item in dic)
- {
- if (item.Key == jsonFieldAttribute.Name)
- {
- Type t = property.PropertyType;
- property.SetValue(entity, ToType(t, item.Value), null);
- break;
- }
- }
- }
- }
- }
- return entity;
- }
- private string Filter(string str)
- {
- if (!(str.StartsWith("\"") && str.EndsWith("\"")))
- {
- return str;
- }
- else
- {
- return str.Substring(1, str.Length - 2);
- }
- }
- public object ToType(Type type, string value)
- {
- if (type == typeof(string))
- {
- return value;
- }
- MethodInfo parseMethod = null;
- foreach (MethodInfo mi in type.GetMethods(BindingFlags.Static
- | BindingFlags.Public))
- {
- if (mi.Name == "Parse" && mi.GetParameters().Length == 1)
- {
- parseMethod = mi;
- break;
- }
- }
- if (parseMethod == null)
- {
- throw new ArgumentException(string.Format(
- "Type: {0} has not Parse static method!", type));
- }
- return parseMethod.Invoke(null, new object[] { value });
- }
- }
- }
最后这是用于测试的代码
- public class Message
- {
- //{ "result": 100, "response": "Who are you?!", "id": 13185569, "msg": "OK." }
- [JsonField(Name = "result")]
- public int Result { get; set; }
- [JsonField(Name = "response")]
- public string Response { get; set; }
- [JsonField(Name = "id")]
- public int Id { get; set; }
- [JsonField(Name = "msg")]
- public string Msg { get; set; }
- }
- class Program
- {
- static void Main(string[] args)
- {
- JsonToInstance util = new JsonToInstance();
- string json = "\"response\":\"我是阿猫酱的小黄鸡\",\"id\":21231513,\"result\":100,\"msg\":\"OK.\"";
- Message m = util.ToInstance<Message>(json);
- }
- }
0 0
- 自定义实现Json字符串向C#对象的转变
- 自定义实现Json字符串向C#对象的转变
- 自定义JsonUtils实现对象和json字符串的相互转换
- 字符串向各个类型的转变
- JSON.NET框架实现C#对象和JSON字符串的转换
- 面向过程和面向对象的二级菜单转变
- 字符串实现转变
- 实现COM组件向Web Services的转变
- 实现COM组件向Web Services的转变
- 实现COM组件向Web Services的转变
- 实现COM组件向Web Services的转变
- 实现COM组件向Web Services的转变
- C# json字符串转为对象
- Android中实现JSON字符串和JSON对象的转换
- python中自定义类对象json字符串化的方法
- C#对象转json字符串和json字符串转对象
- 面向过程向面向对象转变
- 面向过程向面向对象转变
- mysql事务
- [线段树] hdu5195 DZY Loves Topological Sorting
- A problem displaying [localhost] caused Internet Explorer to refresh the webpage using Compatibility
- OpenCms9学习笔记(二)——OpenCms9下载安装
- 第四周 【项目2-分数类的雏形】
- 自定义实现Json字符串向C#对象的转变
- how to change a symbolic link instead of deleting it?
- 基于SSH2框架下的 用户注册 验证码功能
- 开源的PaaS方案:在OpenStack上部署CloudFoundry (四)使用Micro Bosh部署CloudFoundry
- Gson解析错误
- Roope的Cocos2d-x学习之旅 001:基础概念学习——导演、场景、层、精灵
- C++中main函数执行完毕后还可以执行其他语句么?
- Spring - href访问
- 第四周项目三 对象数组操作长方形类