2015-11-27 111 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)这样的东西来获取单个对象。

相关问题