定义用于反序列化json对象的字符串结构嵌套

时间:2015-11-27 18:23:43

标签: c#

这是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.”

有谁能告诉我我做错了什么以及如何正确地反序列化最后一项?

2 个答案:

答案 0 :(得分:1)

JSON.Net期望(当您将集合类型传递给DeserializeObject方法时),根对象是一个数组。根据您的数据,它是一个对象,需要作为单个用户进行处理。

然后你需要将它传递给dataSource,然后你将反序列化的User包装成var userList = new List<User>{user};

答案 1 :(得分:0)

错误消息非常简单。您正在尝试将不是数组(您的JSON字符串)的内容反序列化为集合(List<User>)。它不是一个集合所以你不能这样做。你应该做JsonConvert.DeserializeObject<RootObject>(json)这样的事情来获得一个对象。