转自 http://hi.baidu.com/wjinbd/item/c54d43d998beb33be3108fddjson
1 建立本身要用的类数组
class stu { string _name; int _age; public string name {get{return _name;} set {_name=value;} } public int age { get { return _age; } set { _age = value; } } }
2 使用反射方法spa
public object jsonToObject(string jsonstr, Type objectType)//传递两个参数,一个是json字符串,一个是要建立的对象的类型 { string[] jsons = jsonstr.Split(new char[] { ',' });//将json字符串分解成 “属性:值”数组 for (int i = 0; i < jsons.Length; i++) { jsons[i] = jsons[i].Replace("\"", ""); }//去掉json字符串的双引号 object obj = System.Activator.CreateInstance(typeof(stu)); //使用反射动态建立对象 PropertyInfo[] pis = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);//得到对象的全部public属性 if (pis != null)//若是得到了属性 foreach (PropertyInfo pi in pis)//针对每个属性进行循环 { for (int i = 0; i < jsons.Length; i++)//检查json字符串中的全部“属性:值”类表 { if (jsons[i].Split(new char[] { ':' })[0] == pi.Name)//若是对象的属性名称刚好和json中的属性名相同 { Type proertyType = pi.PropertyType; //得到对象属性的类型 pi.SetValue(obj, Convert.ChangeType(jsons[i].Split(new char[] { ':' })[1], proertyType), null); //将json字符串中的字符串类型的“值”转换为对象属性的类型,并赋值给对象属性 } } } return obj; }
3 调用3d
String jsonstr = "\"name\":\"zhang\",\"age\":\"19\""; stu aa = (stu)jsonToObject(jsonstr, typeof(stu));