JavaScriptSerializer的json格式输出

时间:2017-07-08 10:31:53

标签: c# json

var singleItems = new List<Products>();

singleItems.Add(new Products() { product_id = 1, title = "Bryon Hetrick", price = 50 });
singleItems.Add(new Products() { product_id = 2, title = "Nicole Wilcox", price = 20 });

var serializer = new JavaScriptSerializer();
var serializedResult = serializer.Serialize(serializer);

从上面的示例代码中我得到的Json输出就像下面一样。

[{"product_id":1,"title":"Bryon Hetrick","price":50},
 {"product_id":2,"title":"Nicole Wilcox","price":20}]

但是我的Json还需要一个名为“config”的值,我还需要完全像下面那样格式化的数据。如何编辑我的c#代码来实现该值?

{ "products":[{"product_id":"B071H6TBM5","title":"New Iphone 5S","price":"23.45"},{"product_id":"B071DM968J","title":"Iphone 4 old","price":"23.45"}],"config":{"token":"","Site":"Us","Mode":"ListMyItem"}}

1 个答案:

答案 0 :(得分:0)

您可以使用所需的属性创建一个Config类,然后使用Prodcuts和Config创建一个复合类,即ProductConfig:

public class Products 
{
   public string product_id { get; set; }
   public string title { get; set; }
   public string price { get; set; }
}

public class Config
{
  public string token { get; set; }
  public string site { get; set; }
  public string mode { get; set; }
}

public class ProductConfig 
{
   public List<Products> Products { get; set; }
   public Config Config { get; set; }
}

然后,您可以使用新属性创建/填充ProductConfig类。

public string SerializeProductConfig()
{
   ProductConfig pc = new ProductConfig();
   pc.Config = new Config { token = "DDTest", site = "US", mode = "Test Mode" };
   pc.Products = new List<Products>();
   pc.Products.Add(new Products() { product_id = "1", title = "Bryon Hetrick", price = "50" });
   pc.Products.Add(new Products() { product_id = "2", title = "Nicole Wilcox", price = "20" });

   var serializer = new JavaScriptSerializer();
   return serializer.Serialize(pc);
}

并使用ProductConfig序列化程序或NewtonSoft序列化JavaScript对象,它将为您提供以下JSON

{ // ProductConfig
  "Products": [
    {
      "product_id": "1",
      "title": "Bryon Hetrick",
      "price": "50"
    },
    {
      "product_id": "2",
      "title": "Nicole Wilcox",
      "price": "20"
    }
  ],
  "config": {
    "token": "DDTest",
    "site": "US",
    "mode": "Test Mode"
  }
}