1. 程式人生 > >C# JSON字串序列化與反序列化

C# JSON字串序列化與反序列化

using System.Runtime.Serialization.Json;

using System.Runtime.Serialization;

二、C#將物件序列化成JSON字串

  1. publicstring GetJsonString()  
  2. {  
  3.     List<Product> products = new List<Product>(){  
  4. new Product(){Name="蘋果",Price=5.5},  
  5. new Product(){Name="橘子",Price=2.5},  
  6. new Product(){Name="幹柿子",Price=16.00}  
  7.     };  
  8.     ProductList productlist = new ProductList();  
  9.     productlist.GetProducts = products;  
  10. returnnew JavaScriptSerializer().Serialize(productlist));  
  11. }  
  12. publicclass Product  
  13. {  
  14. publicstring Name { getset; }  
  15. publicdouble Price { getset; }  
  16. }  
  17. publicclass ProductList  
  18. {  
  19. public
     List<Product> GetProducts { getset; }  
這裡主要是使用JavaScriptSerializer來實現序列化操作,這樣我們就可以把物件轉換成Json格式的字串,生成的結果如下:
  1. {"GetProducts":[{"Name":"蘋果","Price":5.5},{"Name":"橘子","Price":2.5},{"Name":"柿子","Price":16}]} 

三、

如何將Json字串轉換成物件使用呢?

在實際開發中,經常有可能遇到用JS傳遞一個Json格式的字串到後臺使用,如果能自動將字串轉換成想要的物件,那進行遍歷或其他操作時,就方便多了。那具體是如何實現的呢?

  1. publicstatic List<T> JSONStringToList<T>(thisstring JsonStr)  
  2. {  
  3.     JavaScriptSerializer Serializer = new JavaScriptSerializer();  
  4.     List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);  
  5. return objs;  
  6. }  
  7. publicstatic T Deserialize<T>(string json)  
  8. {  
  9.     T obj = Activator.CreateInstance<T>();  
  10. using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))  
  11.     {  
  12.         DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());  
  13. return (T)serializer.ReadObject(ms);  
  14.     }  
  15. }  
  16. string JsonStr = "[{Name:'蘋果',Price:5.5},{Name:'橘子',Price:2.5},{Name:'柿子',Price:16}]";  
  17. List<Product> products = new List<Product>();  
  18. products = JSONStringToList<Product>(JsonStr);  
  19. foreach (var item in products)  
  20. {  
  21.     Response.Write(item.Name + ":" + item.Price + "<br />");  
  22. }  
  23. publicclass Product  
  24. {  
  25. publicstring Name { getset; }  
  26. publicdouble Price { getset; }  

在上面的例子中,可以很方便的將Json字串轉換成List物件,操作的時候就方便多了~