2015-11-03 43 views
0

我有一個JSON數組,我正在添加項目。我想以特定的格式顯示這個JSON。關於json數組的問題

我的代碼:

var array = new List<object>(); 
array.Add(new 
     { 
     Dealname = dealname, 
     Ticketcount = tictnum, 
     OriginalPrice = origpri, 
     Dealsticketcount = dealsticktnu, 
     dealprice = dp, 
     totalprice = totamnt, 
     }); 

    array.Add(new 
     { 
     ItemName = itnme, 
     Price = price, 
     Quantity = quant, 
     }); 

這是我的數組類似。我正在添加一些項目。現在,它產生以下輸出:

[{"Dealname":"unnideal","Ticketcount":"25","OriginalPrice":"100","Dealsticketcount":"1","dealprice":"200","totalprice":"300},{"ItemName":"popcorn","Price":"100","Quantity":"1"},{"ItemName":"piza","Price":"100","Quantity":"1"}] 

但我需要我的輸出是這樣的:

[{"Dealname":"unnideal","Ticketcount":"25","OriginalPrice":"100","Dealsticketcount":"1","dealprice":"200","totalprice":"300"},"Offers"[{"ItemName":"popcorn","Price":"100","Quantity":"1"},{"ItemName":"piza","Price":"100","Quantity":"1"}]] 

也就是說,我需要提供一個數組。我怎樣才能使這成爲可能?

回答

0

當Offers需要成爲主對象的一部分時,您的問題似乎是您的父對象和子對象「offer」不相關。

嘗試這樣:

var array = new List<object>(); 
var offers = new List<object>(); 
offers.Add(new 
     { 
     ItemName = itnme, 
     Price = price, 
     Quantity = quant, 
     }); 

array.Add(new 
     { 
     Dealname = dealname, 
     Ticketcount = tictnum, 
     OriginalPrice = origpri, 
     Dealsticketcount = dealsticktnu, 
     dealprice = dp, 
     totalprice = totamnt, 
     Offers = offers 
     }); 
+0

:謝謝你的回答,其做工精細,但它在offers.Some交易的情況下創建複製不要有優惠。 –

+0

@ Unnikrishnan.S那麼沒有優惠的優惠只會爲'Offers'提供一個空/空數組。 –

+0

這是iam獲得的輸出。 [{「Dealname」:「unnideal」,「Ticketcount」:「25」,「OriginalPrice」:「100」,「Dealsticketcount」:「1」,「dealprice」 :「200」 「totalprice」:「300」,「offers」:[{「ItemName」:「popcorn」,「Price」:「100」,「Quantity」:「1」},{「ItemName」 「價格」:「100」,「數量」:「1」}]},{「Dealname」:「megadeal」,「Ticketcount」:「20」,「OriginalPrice」:「100」 Dealsticketcount「 :」1「,」dealprice「:」200「,」totalprice「:」100「,」offers「:[{」ItemName「:」popcorn「,」Price「:」100「,」Quantity「 「1」 },{「ItemName」:「piza」,「Price」:「100」,「Quantity」:「1」}]}] –

0

聽起來像是你只是想命名爲「優惠」的另一個屬性?

var array = new List<object>(); 

var offers = new[] 
{ 
    new {ItemName = itnme, Price = price, Quantity = quant} 
    ... 
}; 

array.Add(new 
    { 
     Dealname = dealname, 
     Ticketcount = tictnum, 
     OriginalPrice = origpri, 
     Dealsticketcount = dealsticktnu, 
     dealprice = dp, 
     totalprice = totamnt, 
     Offers = offers // adding Offers as a property here 
    }); 

這將產生類似下面的JSON:

[ 
    { 
    "Dealname": "unnideal", 
    "Ticketcount": "25", 
    "OriginalPrice": "100", 
    "Dealsticketcount": "1", 
    "dealprice": "200", 
    "totalprice": "300", 
    "Offers": [ 
     { 
     "ItemName": "popcorn", 
     "Price": "100", 
     "Quantity": "1" 
     }, 
     { 
     "ItemName": "piza", 
     "Price": "100", 
     "Quantity": "1" 
     } 
    ] 
    } 
]