- public string GetJsonString()
- {
- List<Product> products = new List<Product>(){
- new Product(){Name="蘋果",Price=5.5},
- new Product(){Name="橘子",Price=2.5},
- new Product(){Name="干柿子",Price=16.00}
- };
- ProductList productlist = new ProductList();
- productlist.GetProducts = products;
- return new JavaScriptSerializer().Serialize(productlist));
- }
- public class Product
- {
- public string Name { get; set; }
- public double Price { get; set; }
- }
- public class ProductList
- {
- public List<Product> GetProducts { get; set; }
- }
這里主要是使用JavaScriptSerializer來實現序列化操作,這樣我們就可以把對象轉換成Json格式的字符串,生成的結果如下:
- {"GetProducts":[{"Name":"蘋果","Price":5.5},{"Name":"橘子","Price":2.5},{"Name":"柿子","Price":16}]}
如何將Json字符串轉換成對象使用呢?
在實際開發中,經常有可能遇到用JS傳遞一個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);
- foreach (var item in products)
- {
- Response.Write(item.Name + ":" + item.Price + "<br />");
- }
- public class Product
- {
- public string Name { get; set; }
- public double Price { get; set; }
- }
在上面的例子中,可以很方便的將Json字符串轉換成List對象,操作的時候就方便多了~