2015-11-27 114 views
-1

這是JSON文件:定義串結構,用於反序列化JSON對象嵌套

{ 
    "Message": { 
    "Code": 200, 
    "Message": "request success" 
    }, 
    "Data": { 
    "USD": { 
     "Jual": "13780", 
     "Beli": "13760" 
    } 
    }, 
    "LastUpdate": "2015-11-27 22:00:11", 
    "ProcessingTime": 0.0794281959534 
} 

我有當我轉換爲類這樣的問題:

 public class Message 
    { 
     public int Code { get; set; } 
     public string Message { get; set; } 
    } 

    public class USD 
    { 
     public string Jual { get; set; } 
     public string Beli { get; set; } 
    } 

    public class Data 
    { 


    public USD USD { get; set; } 
} 

public class RootObject 
{ 
    public Message Message { get; set; } 
    public Data Data { get; set; } 
    public string LastUpdate { get; set; } 
    public double ProcessingTime { get; set; } 
} 

,當我與此反序列化代碼:

private void button1_Click(object sender, EventArgs e) 
     { 
      WebClient wc = new WebClient(); 
      var json = wc.DownloadString(textBox1.Text); 

      List<User> users = JsonConvert.DeserializeObject<List<User>>(json); 
      dataGridView1.DataSource = json; 
     } 

當我運行代碼,我得到一個未處理的異常,其表示:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WindowsFormApp.EmployeeInfo+Areas]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. 
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.」 

任何人都可以告訴我我做錯了什麼以及如何獲得正確的最後一個項目反序列化?

+1

不清楚你在問什麼。你能解釋一下你不明白的錯誤信息部分嗎? –

回答

1

JSON.Net期待(當你通過集合類型的DeserializeObject方法),即根對象是一個數組。根據您的數據,這是一個對象,需要作爲單一用戶進行處理。

然後你需要傳遞的數據源,所以後來你包裹反序列Uservar userList = new List<User>{user};

0

的錯誤信息是非常簡單的。您試圖反序列化的東西是不是一個數組(您的JSON字符串)到一個集合(List<User>)。這不是一個集合,所以你不能這樣做。你應該做一些像JsonConvert.DeserializeObject<RootObject>(json)這樣的東西來獲取單個對象。

相關問題