欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C#教程

當前位置:主頁 > 軟件編程 > C#教程 >

C#實現(xiàn)JSON字符串序列化與反序列化的方法

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C#教程|點擊: 次

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

public string GetJsonString() 
{ 
 List<Product> products = new List<Product>(){ 
 new Product(){Name="蘋果",Price=5}, 
 new Product(){Name="橘子",Price=5}, 
 new Product(){Name="干柿子",Price=00} 
 }; 
 ProductList productlist = new ProductList(); 
 productlistGetProducts = 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來實現(xiàn)序列化操作,這樣我們就可以把對象轉換成Json格式的字符串,生成的結果如下:

復制代碼 代碼如下:

{"GetProducts":[{"Name":"蘋果","Price":5},{"Name":"橘子","Price":5},{"Name":"柿子","Price":16}]}

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

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

public static List<T> JSONStringToList<T>(this string JsonStr) 
{ 
 JavaScriptSerializer Serializer = new JavaScriptSerializer(); 
 List<T> objs = SerializerDeserialize<List<T>>(JsonStr); 
 return objs; 
} 
 
public static T Deserialize<T>(string json) 
{ 
 T obj = ActivatorCreateInstance<T>(); 
 using (MemoryStream ms = new MemoryStream(EncodingUTFGetBytes(json))) 
 { 
 DataContractJsonSerializer serializer = new DataContractJsonSerializer(objGetType()); 
 return (T)serializerReadObject(ms); 
 } 
} 
 
string JsonStr = "[{Name:'蘋果',Price:5},{Name:'橘子',Price:5},{Name:'柿子',Price:16}]"; 
List<Product> products = new List<Product>(); 
products = JSONStringToList<Product>(JsonStr); 
 
foreach (var item in products) 
{ 
 ResponseWrite(itemName + ":" + itemPrice + "<br />"); 
} 
 
public class Product 
{ 
 public string Name { get; set; } 
 public double Price { get; set; } 
} 

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持我們。

上一篇:C# Resources資源詳解

欄    目:C#教程

下一篇:C#數(shù)組中List, Dictionary的相互轉換問題

本文標題:C#實現(xiàn)JSON字符串序列化與反序列化的方法

本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/6047.html

網(wǎng)頁制作CMS教程網(wǎng)絡編程軟件編程腳本語言數(shù)據(jù)庫服務器

如果侵犯了您的權利,請與我們聯(lián)系,我們將在24小時內進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權所有