静态类: public static class jsonToCsharp
{ public static List<T> JSONStringToList<T>(this string JsonStr)
{
JavaScriptSerializer Serializer = new JavaScriptSerializer();
List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);
return objs;
} public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}
}然后在另外一个类中调用using jsonToCsharp;
......
......
string JsonStr = "[{Name:'苹果',Price:5.5},{Name:'橘子',Price:2.5},{Name:'柿子',Price:16}]";
List<Product> products = new List<Product>();
products = jsonToCsharp.JSONStringToList<Product>(JsonStr);错误:命名空间“jsonToCsharp”中不存在类型或命名空间名称“JSONStringToList”。是否缺少程序集引用?
求指导
{ public static List<T> JSONStringToList<T>(this string JsonStr)
{
JavaScriptSerializer Serializer = new JavaScriptSerializer();
List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);
return objs;
} public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}
}然后在另外一个类中调用using jsonToCsharp;
......
......
string JsonStr = "[{Name:'苹果',Price:5.5},{Name:'橘子',Price:2.5},{Name:'柿子',Price:16}]";
List<Product> products = new List<Product>();
products = jsonToCsharp.JSONStringToList<Product>(JsonStr);错误:命名空间“jsonToCsharp”中不存在类型或命名空间名称“JSONStringToList”。是否缺少程序集引用?
求指导
改为:
products = jsonToCsharp.jsonToCsharp.JSONStringToList<Product>(JsonStr);
为啥同一个类的两个静态方法,一个用了扩展,一个却不用扩展?顺带List<Product> products = new List<Product>();这种写法最坑
你下面是通过赋值给products ,所以你这个new永远都是浪费