usingSystem.IO;
usingSystem.Web.Script.Serialization;
usingSystem.Runtime.Serialization.Json;
//工具类
publicstaticList<T> JSONStringToList<T>(thisstring JsonStr)
{
JavaScriptSerializer Serializer = newJavaScriptSerializer();
List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);
return objs;
}
publicstatic T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = newMemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = newDataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}
好了,我们来测试下
stringJsonStr = "[{Name:'苹果',Price:5.5},{Name:'橘子',Price:2.5},{Name:'柿子',Price:16}]";
List<Product> products = newList<Product>();
products = JSONStringToList<Product>(JsonStr);
//Response.Write(products.Count());
foreach(var item in products)
{
Response.Write(item.Name + ":" + item.Price + "<br />");
}
//实体类
public class Product
{
publicstring Name { get; set; }
publicdouble Price { get; set; }
}
结果:
苹果:5.5橘子:2.5柿子:16