C#实现JSON字符串序列化与反序列化的方法
C#将对象序列化成JSON字符串
publicstringGetJsonString()
{
List<Product>products=newList<Product>(){
newProduct(){Name="苹果",Price=5},
newProduct(){Name="橘子",Price=5},
newProduct(){Name="干柿子",Price=00}
};
ProductListproductlist=newProductList();
productlistGetProducts=products;
returnnewJavaScriptSerializer()Serialize(productlist));
}
publicclassProduct
{
publicstringName{get;set;}
publicdoublePrice{get;set;}
}
publicclassProductList
{
publicList<Product>GetProducts{get;set;}
}
这里主要是使用JavaScriptSerializer来实现序列化操作,这样我们就可以把对象转换成Json格式的字符串,生成的结果如下:
{"GetProducts":[{"Name":"苹果","Price":5},{"Name":"橘子","Price":5},{"Name":"柿子","Price":16}]}
如何将Json字符串转换成对象使用呢?
在实际开发中,经常有可能遇到用JS传递一个Json格式的字符串到后台使用,如果能自动将字符串转换成想要的对象,那进行遍历或其他操作时,就方便多了。那具体是如何实现的呢?
publicstaticList<T>JSONStringToList<T>(thisstringJsonStr)
{
JavaScriptSerializerSerializer=newJavaScriptSerializer();
List<T>objs=SerializerDeserialize<List<T>>(JsonStr);
returnobjs;
}
publicstaticTDeserialize<T>(stringjson)
{
Tobj=ActivatorCreateInstance<T>();
using(MemoryStreamms=newMemoryStream(EncodingUTFGetBytes(json)))
{
DataContractJsonSerializerserializer=newDataContractJsonSerializer(objGetType());
return(T)serializerReadObject(ms);
}
}
stringJsonStr="[{Name:'苹果',Price:5},{Name:'橘子',Price:5},{Name:'柿子',Price:16}]";
List<Product>products=newList<Product>();
products=JSONStringToList<Product>(JsonStr);
foreach(variteminproducts)
{
ResponseWrite(itemName+":"+itemPrice+"<br/>");
}
publicclassProduct
{
publicstringName{get;set;}
publicdoublePrice{get;set;}
}
在上面的例子中,可以很方便的将Json字符串转换成List对象,操作的时候就方便多了~
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。