C#将Json字符串反序列化成List对象类集合

C#Json字符串反序列化成List对象类集合

 

using System.IO;

using System.Web.Script.Serialization;

using System.Runtime.Serialization.Json;

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);

        }

}

好了,我们来测试下

string JsonStr = "[{Name:'苹果',Price:5.5},{Name:'橘子',Price:2.5},{Name:'柿子',Price:16}]";

List<Product> products = new List<Product>();

products = JSONStringToList<Product>(JsonStr);

//Response.Write(products.Count());

foreach (var item in products)

{

Response.Write(item.Name + ":" + item.Price + "<br />");

}

public class Product

{

public string Name { getset; }

public double Price { getset; }

}

结果:

苹果:5.5
橘子
:2.5
柿子:16

//转载于http://www.rczjp.cn/HTML/110126/20110226120213.html

posted @ 2012-02-29 11:07  leidc  阅读(724)  评论(0编辑  收藏  举报