2014-05-09 135 views
1

我一直在試圖反序列化使用JSON.Net反序列化JSON與JSON.NET發出

在C#中的JSON流我有一個JObject「JO1」當我做一個JO1.ToString()上該字符串的內容是:

{ 
    "Successful": true, 
    "Value": [ 
    { 
     "no": "1", 
     "name": "Accounting" 
    }, 
    { 
     "no": "2", 
     "name": "Marketing" 
    }, 
    { 
     "no": "3", 
     "name": "Information Technology" 
    } 
    ] 
} 

我試過下面的.NET代碼無濟於事。

public class main() 
{ 
    public void main() 
    { 
    JObject jo = new JObject(); 
    jo = functionthatretrievestheJSONdata(); 

    List<departments> dt1 = JsonConvert.DeserializeObject<List<departments>>(jo.ToString()); 
    } 
} 

public class departments 
{ 
    public int no { get; set; } 
    public string name { get; set; } 
} 

有人能請給我一個正確的方向指針嗎?

回答

5

你會需要一個類來包裝List<departments>,像這樣:

public class DeserializedDepartments 
{ 
    public bool Successful { get; set; } 
    public List<departments> Value { get; set; } 
} 

等你反序列化這樣的:

DeserializedDepartments dt1 = 
    JsonConvert.DeserializeObject<DeserializedDepartments>(jo.ToString()); 

現在你List<departments>是的Valuedt1;或dt1.Value

+1

+1我正要鍵入相同的:) – Halvard

+0

+1非常快..... –

2

您沒有考慮到該列表是附加到另一個對象的數組。

你有一個名爲Successful的布爾值的對象和一個名爲Value的部門數組。

試試這個:

public class main() 
{ 
    public void main() 
    { 
     JObject jo = new JObject(); 
     jo = functionthatretrievestheJSONdata(); 

     Results dt1 = JsonConvert.DeserializeObject<Results>(jo.ToString()); 
     var depts = dt1.Value; 
    } 
} 

public class Results 
{ 
    public bool Successful {get;set;} 
    public List<Department> Value {get;set;} 
} 

public class Department 
{ 
    public int no { get; set; } 
    public string name { get; set; } 
}