C# JSON字串序列化與反序列化
阿新 • • 發佈:2019-01-03
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
二、C#將物件序列化成JSON字串
- publicstring 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;
- returnnew JavaScriptSerializer().Serialize(productlist));
- }
- publicclass Product
- {
- publicstring Name { get; set; }
- publicdouble Price { get; set; }
- }
- publicclass ProductList
- {
-
public
- }
- {"GetProducts":[{"Name":"蘋果","Price":5.5},{"Name":"橘子","Price":2.5},{"Name":"柿子","Price":16}]}
三、
如何將Json字串轉換成物件使用呢?
在實際開發中,經常有可能遇到用JS傳遞一個Json格式的字串到後臺使用,如果能自動將字串轉換成想要的物件,那進行遍歷或其他操作時,就方便多了。那具體是如何實現的呢?
- publicstatic List<T> JSONStringToList<T>(thisstring JsonStr)
- {
- JavaScriptSerializer Serializer = new JavaScriptSerializer();
- List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);
- return objs;
- }
- publicstatic 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 />");
- }
- publicclass Product
- {
- publicstring Name { get; set; }
- publicdouble Price { get; set; }
- }
在上面的例子中,可以很方便的將Json字串轉換成List物件,操作的時候就方便多了~