C#实现JSON字符串序列化与反序列化的方法

所属分类: 软件编程 / C#教程 阅读数: 44
收藏 0 赞 0 分享

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来实现序列化操作,这样我们就可以把对象转换成Json格式的字符串,生成的结果如下:

复制代码 代码如下:

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

如何将Json字符串转换成对象使用呢?

在实际开发中,经常有可能遇到用JS传递一个Json格式的字符串到后台使用,如果能自动将字符串转换成想要的对象,那进行遍历或其他操作时,就方便多了。那具体是如何实现的呢?

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#使用oledb读取excel表格内容到datatable的方法

这篇文章主要介绍了C#使用oledb读取excel表格内容到datatable的方法,涉及C#操作oledb及datatable的相关技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#使用oledb操作excel文件的方法

这篇文章主要介绍了C#使用oledb操作excel文件的方法,涉及C#中oledb操作excel的相关技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C#使用IHttpModule接口修改http输出的方法

这篇文章主要介绍了C#使用IHttpModule接口修改http输出的方法,涉及C#操作IHttpModule接口的相关技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C#给图片加水印的简单实现方法

这篇文章主要介绍了C#给图片加水印的简单实现方法,涉及C#操作图片的相关技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C#生成随机数的方法小结

这篇文章主要介绍了C#生成随机数的方法,实例总结了C#生成随机数的相关技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C#使用jQuery实现无刷新评论提交的方法

这篇文章主要介绍了C#使用jQuery实现无刷新评论提交的方法,涉及C#结合jQuery进行Ajax操作的相关技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C#读取中文文件出现乱码的解决方法

这篇文章主要介绍了C#读取中文文件出现乱码的解决方法,涉及C#中文编码的操作技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C#图像对比度调整的方法

这篇文章主要介绍了C#图像对比度调整的方法,涉及C#实现图像对比度操作的相关技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#图像灰度级拉伸的方法

这篇文章主要介绍了C#图像灰度级拉伸的方法,涉及C#灰度操作的相关技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#图像线性变换的方法

这篇文章主要介绍了C#图像线性变换的方法,涉及C#操作图像线性变换的相关技巧,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多