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

usingSystem.Web.Script.Serialization;

publicvoid ProcessRequest(HttpContext context)

{

        context.Response.ContentType = "text/plain";

         

        List<Product> products = newList<Product>(){

        new Product(){Name="苹果",Price=5.5},

        new Product(){Name="橘子",Price=2.5},

    new Product(){Name="干柿子",Price=16.00}

        };

        ProductList productlist = newProductList();

        productlist.GetProducts = products;

        context.Response.Write(newJavaScriptSerializer().Serialize(productlist));

}

publicbool IsReusable

{

     get

  {

          returnfalse;

  }   

}

 

//实体类

public class Product

{

        publicstring Name { getset; }

        publicdouble Price { getset; }

}

public class ProductList

{

    publicList<Product> GetProducts { getset; }

}

 

生成的JSON结果如下:

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

 

你可能感兴趣的:(C#对象序列化成JSON字符串)