C#實現(xiàn)JSON字符串序列化與反序列化的方法
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é)果如下:
{"GetProducts":[{"Name":"蘋果","Price":5},{"Name":"橘子","Price":5},{"Name":"柿子","Price":16}]}
如何將Json字符串轉(zhuǎn)換成對象使用呢?
在實際開發(fā)中,經(jīng)常有可能遇到用JS傳遞一個Json格式的字符串到后臺使用,如果能自動將字符串轉(zhuǎn)換成想要的對象,那進(jì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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
DevExpress實現(xiàn)TreeList父子節(jié)點(diǎn)CheckState狀態(tài)同步的方法
這篇文章主要介紹了DevExpress實現(xiàn)TreeList父子節(jié)點(diǎn)CheckState狀態(tài)同步的方法,需要的朋友可以參考下2014-08-08
C#關(guān)聯(lián)自定義文件類型到應(yīng)用程序并實現(xiàn)自動導(dǎo)入功能
今天通過本文給大家分享C#關(guān)聯(lián)自定義文件類型到應(yīng)用程序并實現(xiàn)自動導(dǎo)入功能,代碼中寫入了兩個注冊表,實例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-09-09
C#實現(xiàn)掃描局域網(wǎng)內(nèi)的所有IP和端口
這篇文章主要為大家詳細(xì)介紹了如何利用C#實現(xiàn)掃描局域網(wǎng)內(nèi)的所有IP和端口的功能,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下2022-12-12

