国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

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

2019-10-29 21:16:08
字體:
供稿:網(wǎng)友

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)序列化操作,這樣我們就可以把對象轉(zhuǎn)換成Json格式的字符串,生成的結(jié)果如下:

 

復(fù)制代碼 代碼如下:

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

 

如何將Json字符串轉(zhuǎn)換成對象使用呢?

在實際開發(fā)中,經(jīng)常有可能遇到用JS傳遞一個Json格式的字符串到后臺使用,如果能自動將字符串轉(zhuǎn)換成想要的對象,那進行遍歷或其他操作時,就方便多了。那具體是如何實現(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字符串轉(zhuǎn)換成List對象,操作的時候就方便多了~

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。


注:相關(guān)教程知識閱讀請移步到c#教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 阿拉善右旗| 铁力市| 博白县| 淳安县| 乐都县| 仪征市| 铜鼓县| 岱山县| 香港 | 普定县| 正蓝旗| 安溪县| 景谷| 永修县| 克东县| 鄢陵县| 都安| 天长市| 南郑县| 洪泽县| 偃师市| 连南| 鹤庆县| 若羌县| 且末县| 嵩明县| 湖南省| 武夷山市| 菏泽市| 东光县| 望谟县| 炉霍县| 潜山县| 纳雍县| 伽师县| 葫芦岛市| 乌兰浩特市| 福州市| 罗山县| 武义县| 固原市|