Getting “because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly” error when deserializing a Json object

拜拜、爱过 提交于 2019-12-05 14:23:42

You are getting this error because your JSON is hierarchical while your class is essentially flat. If you use JSONLint.com to validate and reformat the JSON, you can see the structure better:

{
    "results": [
        {
            "series": [
                {
                    "name": "PWR_00000555",
                    "columns": [
                        "time",
                        "last"
                    ],
                    "values": [
                        [
                            "1970-01-01T00:00:00Z",
                            72
                        ]
                    ]
                }
            ]
        }
    ]
}

This corresponds to the following class structure (which I initially generated using json2csharp.com, then manually edited to add the [JsonProperty] attributes):

public class RootObject
{
    [JsonProperty("results")]
    public List<Result> Results { get; set; }
}

public class Result
{
    [JsonProperty("series")]
    public List<Series> Series { get; set; }
}

public class Series
{
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("columns")]
    public List<string> ColumnNames { get; set; }
    [JsonProperty("values")]
    public List<List<object>> Points { get; set; }
}

You can deserialize your JSON into the above class structure like this:

var root = JsonConvert.DeserializeObject<RootObject>(jsonString);

Fiddle: https://dotnetfiddle.net/50Z64s

If you're willing to sacrifice IntelliSense and compile time type safety, then you can simply deserialize the JSON into a dynamic object:

dynamic parsed = JsonConvert.DeserializeObject(jsonString);
PrintAllNames(parsed);

//...

private void PrintAllNames(dynamic obj)
{
    foreach(var result in obj.results)
        foreach(var item in result.series)
            Console.WriteLine(item.name);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!