2013-06-22 48 views
0

我使用Newtonsoft Json.Net反序列化JSON進料引入對象:反序列化複雜JSON對象與字典

JSON:

staticKey1: value, 
staticKey2: value, 

results: [ 
{ 
    key1: value1, 
    key2: value2, 
    key3: value3, 
... 
    keyN: valueN 
} 
], 

C#類:

public class MyClassName 
{ 
    public string staticKey1 { get; set; } 
    public string staticKey2 { get; set; } 
    public Dictionary<String, String> results { get; set; } 
} 

我使用Newtonsoft.Json.JsonConvert.DeserializeObject(),但我收到異常:

無法反序列化當前的JSON數組(例如,因爲該類型需要一個JSON對象(例如{「name」:「value」}),因此該類型需要一個類型爲 'System.Collections.Generic.Dictionary`2 [System.String,System.String]' )到 反序列化正確。要修復此錯誤,請將JSON更改爲 JSON對象(例如{「name」:「value」}),或者將反序列化類型更改爲 數組或實現集合接口的類型(例如 ICollection,IList)可以從JSON 數組反序列化的列表。也可以將JsonArrayAttribute添加到該類型中,以強制它從一個JSON數組反向序列化爲 。

回答

1

其實它很容易,用途:

public class MyClass 
{ 
    public string staticKey1 { get; set; } 
    public string staticKey2 { get; set; } 
    public IEnumerable<IDictionary<string, string>> results { get; set; } 
} 

但也許有更好的解決方案。