2016-03-10 61 views
0

請告訴我,我怎麼了JSON這樣的:C#動態ExpandoObject陣列

dynamic packet = new ExpandoObject(); 
    packet.type = "somethink"; 
    packet.user = 12345; 

    packet.nets[0].amout = 123; 
    packet.nets[0].lower = 0; 
    packet.nets[1].amout = 345; 
    packet.nets[1].lower = 1; 
    string input = Newtonsoft.Json.JsonConvert.SerializeObject(packet); 

它不是workig,錯誤: 在系統類型「Microsoft.CSharp.RuntimeBinder.RuntimeBinderException」未處理的異常.Core.dll

欲瞭解更多信息: 「System.Dynamic.ExpandoObject」 不包含 「網」

感謝的定義。

回答

4

這是ExpandoObject誰是動態對象。性能的其餘部分應該是其他ExpandoObject實例或定期對象,數組,集合...

例如:

packet.nets = new[] 
{ 
    new { amount = 123, lower = 0 }, 
    new { amount = 345, lower = 1 } 
} 

或者:

packet.nets = new[] 
{ 
    new Dictionary<string, int> { { "amount", 345 }, { "lower", 0 } }, 
    new Dictionary<string, int> { { "amount", 123 }, { "lower", 1 } } 
} 

是有很多其他方法,包括使用具體類的實例。

0

您首先需要聲明網。例如

packet.nets = new Dictionary<int, dynamic>();

然後,你需要實例網

packet.nets[0] = new {amount = 123, lower = 0};

的情況下,結果是

dynamic packet = new ExpandoObject(); 
packet.type = "somethink"; 
packet.user = 12345; 

packet.nets = new Dictionary<int, dynamic>(); 
packet.nets[0] = new { amount = 123, lower = 0 }; 
packet.nets[1] = new { amount = 345, lower = 1 }; 
+0

爲什麼值應該是'dynamic'? –

+0

@MatíasFidemraizer我猜他們可以是對象,相同的區別。無論如何,你的代碼自動數組啓動可能比將其聲明爲字典更好。唯一的是你可以刪除'object'部分,編譯器會假設它。不知道爲什麼你得到了贊成,我upvoted。 –

+0

嘿,是的,我已經將代碼轉換爲按照用法進行類型推斷。在我的情況下,我會聲明值類型爲「動態」,如果他們應該稍後訪問。如果只是爲了序列化,誰在乎,'object'也可以做得很好 –

2

首先,你需要在packet對象創建nets ,像這樣:

packet.nets = new dynamic[2]; 

而且在nets,初始化的對象,如果你想用`ExpandoObject太:

packet.nets[0] = new ExpandoObject(); 
packet.nets[1] = new ExpandoObject(); 

然後完成後,完整的代碼:

dynamic packet = new ExpandoObject(); 
packet.type = "somethink"; 
packet.user = 12345; 

packet.nets = new dynamic[2]; 

packet.nets[0] = new ExpandoObject(); 
packet.nets[0].amout = 123; 
packet.nets[0].lower = 0; 

packet.nets[1] = new ExpandoObject(); 
packet.nets[1].amout = 345; 
packet.nets[1].lower = 1;    

string input = Newtonsoft.Json.JsonConvert.SerializeObject(packet);