雷火电竞-中国电竞赛事及体育赛事平台

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

C#教程

當(dāng)前位置:主頁(yè) > 軟件編程 > C#教程 >

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

來(lái)源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C#教程|點(diǎn)擊:

C#將對(duì)象序列化成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來(lái)實(shí)現(xiàn)序列化操作,這樣我們就可以把對(duì)象轉(zhuǎn)換成Json格式的字符串,生成的結(jié)果如下:

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

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

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

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

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。

上一篇:C# Resources資源詳解

欄    目:C#教程

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

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

本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/6047.html

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

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

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

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