2015-11-03 77 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" 
     } 
    ] 
    } 
]