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

作者:笨笨丁 时间:2023-12-01 12:40:23 

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对象,操作的时候就方便多了~

来源:http://www.cnblogs.com/dwfbenben/archive/2013/06/06/3122662.html

标签:c#,json,反序列化,序列化
0
投稿

猜你喜欢

  • Android编程实现加载等待ProgressDialog的方法

    2022-09-11 21:12:11
  • synchronized及JUC显式locks 使用原理解析

    2023-08-05 03:28:41
  • SpringMVC实现文件上传和下载功能

    2022-10-03 18:22:27
  • Java并发编程之JUC并发核心AQS同步队列原理剖析

    2023-01-15 15:14:37
  • Android实现简单画中画功能

    2022-07-18 04:51:25
  • 浅谈redis key值内存消耗以及性能影响

    2022-11-09 20:35:17
  • centos7下安装java及环境变量配置技巧

    2022-06-05 08:06:13
  • Java Object类中的常用API介绍

    2023-11-09 01:51:00
  • Android ListView适配器(Adapter)优化方法详解

    2023-08-09 21:44:32
  • Spring Boot教程之利用ActiveMQ实现延迟消息

    2023-11-23 18:25:09
  • Input系统之InputReader处理按键事件详解

    2023-11-09 20:57:05
  • Activity取消界面切换的默认动画方法(推荐)

    2021-05-23 12:12:52
  • C#使用GET、POST请求获取结果

    2023-04-20 13:35:43
  • java泛型的局限探究及知识点总结

    2021-11-29 03:43:32
  • c#实现sqlserver事务处理示例

    2022-03-28 19:39:50
  • Android手机开发设计之记事本功能

    2023-12-10 21:47:00
  • java实现动态代理示例分享

    2023-04-28 15:54:49
  • RecyclerView上拉加载封装代码

    2023-05-08 21:02:05
  • 不安装excel使用c#创建excel文件

    2023-02-20 07:03:25
  • java中List删除时需要的注意事项

    2023-11-11 01:28:00
  • asp之家 软件编程 m.aspxhome.com