2012-06-17 54 views
1

我收到了一個JSON文件,其中包含一個根元素「users」和一個「user」項列表。使用Json.NET對自定義對象數組反序列化JSON

我試圖反序列化一個名爲User的自定義類的List,但我一直得到JsonSerializationException,它無法覆蓋它。

我試過如下:

代碼:

public class User 
{ 
    public int ID { get; set; } 
    public bool Active { get; set; } 
    public string Name { get; set; } 
} 

public class Response 
{ 
    public List<User> Users { get; set; } 
    public JObject Exception { get; set; } 
} 

而且 -

public Response DeserializeJSON(string json) 
    { 
     Response deserialized = JsonConvert.DeserializeObject<Response>(json); 
     return deserialized; 
    } 

JSON:

{ 
    "Users": { 
     "User": [ 
      { 
      "id": "1", 
      "active": "true", 
      "name": "Avi" 
      }, 
      { 
      "id": "2", 
      "active": "false", 
      "name": "Shira" 
      }, 
      { 
      "id": "3", 
      "active": "false", 
      "name": "Moshe" 
      }, 
      { 
      "id": "4", 
      "active": "false", 
      "name": "Kobi" 
      }, 
      { 
      "id": "5", 
      "active": "true", 
      "name": "Yael" 
      } 
     ] 
     } 
} 

對不起,壞的造型!

+0

你確定JSON是有效的嗎?嘗試在http://jsonlint.com/這裏傾倒它,看看它在JSON本身沒有一些問題。 –

+0

這是我做的第一件事:)它的確是有效的。 – user1461793

回答

0

在您的Response類中,嘗試在構造函數中初始化集合。

public class Response 
{ 
    public Response() 
    { 
     Users = new List<User>(); 
    } 
    public IEnumerable<User> Users { get; set; } 
    public JObject Exception { get; set; } 
} 
+0

不,沒有幫助...同樣的錯誤。會是什麼呢??? – user1461793

+0

接下來要嘗試的是保留上面的代碼,但將集合類型更改爲IEnumerable(保留爲構造函數中的List)。我已編輯上述解決方案 – BlackSpy

+0

仍然無法正常工作。在調試時,它確實到達Response的構造函數,但列表保持爲空。 – user1461793

0

唉唉,我需要開始閱讀JSON更好... :) 我的問題是,有INFACT 2「包裝」這個JSON字符串:

的根元素是「用戶」,這擁有一個名爲「用戶」的元素。 固定它:

public class User 
{ 
    public int id { get; set; } 
    public bool active { get; set; } 
    public string name { get; set; } 
} 

public class Response 
{ 
    public ResponseContent users { get; set; } 
} 

public class ResponseContent 
{ 
    public List<User> user; 
} 

謝謝! :)