C#將對象序列化成JSON字符串


  1. public string 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.     return new JavaScriptSerializer().Serialize(productlist));  
  11. }  
  12.  
  13. public class Product  
  14. {  
  15.     public string Name { get; set; }  
  16.     public double Price { get; set; }  
  17. }  
  18.  
  19. public class ProductList  
  20. {  
  21.     public List<Product> GetProducts { get; set; }  

這里主要是使用JavaScriptSerializer來實現序列化操作,這樣我們就可以把對象轉換成Json格式的字符串,生成的結果如下:

  1. {"GetProducts":[{"Name":"蘋果","Price":5.5},{"Name":"橘子","Price":2.5},{"Name":"柿子","Price":16}]} 

 

如何將Json字符串轉換成對象使用呢?

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

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM