2017-07-08 115 views
1
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輸出像波紋管。從JavaScriptSerializer輸出json格式

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

但我的Json需要一個更多的值 - 「配置」,我也需要格式化完全像波紋管的整個數據。如何編輯我的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"}} 

回答

0

你可以做一個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); 
} 

,並使用JavaScript串行或NewtonSoft,這將給你的序列化對象ProductConfig以下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" 
    } 
} 
+0

有沒有辦法做到這一點而不使其模型類? –

+0

@Johnpoe - 序列化程序查看您提供的對象並將其轉換爲JSON,因此您必須修改您的RegisteredUsers類以包含輸出的Config屬性。這可能會打破你的設計,所以我會建議有一箇中間班,如我的答案中所示。 –

+0

我編輯了這個問題。 –