2012-11-07 25 views
1

我試圖反序列化以下JSON響應反序列化JSON數據:然而含有不同數量的參數爲C#(使用Json.NET)

[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads", "0":"Yes", "1":"No"} … ] 

產生的問題,在一個事實,即數的以下參數「類別」可以從0變化到10的含義的所有以下是可能的JSON響應:

[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads"} … ] 
[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads", "0":"Yes", "1":"No"} … ] 
[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads", "0":"Bad", "1":"OK", "2":"Good", "3":"Very good"} … ] 

我反序列化響應以下形式的對象:

class Poll 
    { 
     public int pollid { get; set; } 
     public string question { get; set; } 
     public DateTime start { get; set; } 
     public DateTime end { get; set; } 
     public string category { get; set; } 

     [JsonProperty("0")] 
     public string polloption0 { get; set; } 
     [JsonProperty("1")] 
     public string polloption1 { get; set; } 
     [JsonProperty("2")] 
     public string polloption2 { get; set; } 
     [JsonProperty("3")] 
     public string polloption3 { get; set; } 
     [JsonProperty("4")] 
     public string polloption4 { get; set; } 
     [JsonProperty("5")] 
     public string polloption5 { get; set; } 
     [JsonProperty("6")] 
     public string polloption6 { get; set; } 
     [JsonProperty("7")] 
     public string polloption7 { get; set; } 
     [JsonProperty("8")] 
     public string polloption8 { get; set; } 
     [JsonProperty("9")] 
     public string polloption9 { get; set; } 
    } 

我的問題是:是否有更好的方法來處理不同數量的參數存儲?擁有10個可能使用也可能不使用的類屬性(取決於響應)看起來像是這樣的「黑客」。

任何幫助將真正感激!

非常感謝, 特德

+1

您是否考慮重新設計JSON對象格式並將這些值包含在數組中? –

+1

不幸的是,我無法控制提供者提供數據的方式 - 我只能使用它。 (如果這是你的建議?)。 – Bataleon

回答

0

您可以容納可變數量的屬性和數組

有類似

List<string>(); 
你把所有polloption1,polloption2的

...您可以將json反序列化爲動態類型

dynamic d = JObject.Parse(json); 

和訪問你知道存在的屬性

d.pollid, d.start, d.category ... 
+0

感謝您的回覆。我會嘗試使用動態類型。我有一種感覺可能會出現問題,因爲我必須按順序使用[JsonProperty(「0」)]關鍵字來使C#正確地將JSON參數與對象屬性相關聯。 – Bataleon

+0

或將polloption1,polloption2 ...屬性保存爲列表() – Mihai

+0

並請記住標記爲「已回答」,如果我的回答有幫助:) – Mihai

0

是否有可能是一個更好的方式來處理不同數量的參數的存儲?

您可以反序列化爲ExpandoObjectdynamic例如,

var serializer = new JavaScriptSerializer(); 
var result = serializer.Deserialize<dynamic>(json); 
foreach (var item in result) 
{ 
    Console.WriteLine(item["question"]); 
} 
+0

感謝您的回覆。我會給動態類型一個嘗試。 – Bataleon

相關問題