Json的序列化与反序列化

C#Json字符串反序列化成List对象类集合

复制代码
using System.IO;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;
public static List<T> JSONStringToList<T>(this string JsonStr)
    {
        JavaScriptSerializer Serializer = new JavaScriptSerializer();
        List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);
        return objs;
    }
 
    public static T Deserialize<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            return (T)serializer.ReadObject(ms);
        }
}
复制代码

好了,我们来测试下

复制代码
string JsonStr = "[{Name:'苹果',Price:5.5},{Name:'橘子',Price:2.5},{Name:'柿子',Price:16}]";
List<Product> products = new List<Product>();
products = JSONStringToList<Product>(JsonStr);
//Response.Write(products.Count());
foreach (var item in products)
{
   Response.Write(item.Name + ":" + item.Price + "<br />");
}
public class Product
{
   public string Name { get; set; }
   public double Price { get; set; }
}
复制代码

结果:

苹果:5.5
橘子
:2.5
柿子:16

 

==============================

C#将对象序列化成JSON字符串

 

复制代码
using System.Web.Script.Serialization;
public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
 
            List<Product> products = new List<Product>(){
            new Product(){Name="苹果",Price=5.5},
            new Product(){Name="橘子",Price=2.5},
new Product(){Name="干柿子",Price=16.00}
            };
            ProductList productlist = new ProductList();
            productlist.GetProducts = products;
            context.Response.Write(new JavaScriptSerializer().Serialize(productlist));
        }
public bool IsReusable
{
get
{
                return false;
}
}
 
        public class Product
        {
            public string Name { get; set; }
            public double Price { get; set; }
        }
 
        public class ProductList
        {
            public List<Product> GetProducts { get; set; }
        }
 
复制代码

 

生成的JSON结果如下:

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

 

来源:
http://www.rczjp.cn/HTML/110126/20110226120213.html
http://www.rczjp.cn/HTML/101201/20104701014751.html

posted @   三台  阅读(324)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示