简体   繁体   English

如何在 c# 中正确反序列化 Json

[英]How to deserialize Json correctly in c#

Good afternoon.下午好。 I need to deserialize the fields in JSON so that I can work with them as variables.我需要反序列化 JSON 中的字段,以便我可以将它们作为变量使用。 I wrote a getter and setter for fields, loaded json from the url, but at the deserialization stage I get an error我为字段编写了一个 getter 和 setter,从 url 加载了 json,但在反序列化阶段出现错误

"Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (eg [1,2,3]) into type 'GetDataFromUrl.JsonData' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly." "Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (eg [1,2,3]) into type 'GetDataFromUrl.JsonData' because the type requires a JSON object (eg {"name":"value"})正确反序列化。”

How do I correctly specify data for deserialization?如何正确指定反序列化数据?

This type of JSON:这种类型的 JSON:

[
    {
        "Date": "2020-01-30",
        "CountProblem": 10,
        "Users": 8,
    }
]

Code:代码:

class JsonData
{
    public DateTime Date { get; set; }
    public int CountProblem { get; set; }
    public int Users { get; set; }
}

    class Report
{
    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        var urlResponse = client.DownloadString("//my url");

        JsonData jsondata = JsonConvert.DeserializeObject<JsonData>(urlResponse);

        DateTime date = jsondata.Date;
        int problemCount = jsondata.CountProblem;
        int Users = jsondata.Users;

        Console.WriteLine(Date + "," + CountProblem + "," + Users);
    }

Your json string represents array not a single object, so try:您的 json 字符串表示数组而不是单个 object,因此请尝试:

List<JsonData> jsondata = JsonConvert.DeserializeObject<List<JsonData>>(urlResponse);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM