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/101201/20104701014751.htmls

posted @ 2012-02-29 11:14  leidc  阅读(322)  评论(0编辑  收藏  举报