gpt4 book ai didi

c# - 反序列化 Json 对象时出现 "because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly"错误

转载 作者:太空狗 更新时间:2023-10-29 23:58:50 25 4
gpt4 key购买 nike

请帮帮我。我在哪里缺少信息?我需要反序列化以下 JSON 字符串。

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

为此,我定义了我的类:

public class Serie
{
public Serie()
{
this.Points = new List<object[]>();
}

[JsonProperty(PropertyName = "results")]
public string results { get; set; }

[JsonProperty(PropertyName = "series")]
public string sries { get; set; }


[JsonProperty(PropertyName = "name")]
public string Name { get; set; }

[JsonProperty(PropertyName = "columns")]
public string[] ColumnNames { get; set; }

[JsonProperty(PropertyName = "values")]
public List<object[]> Points { get; set; }

但是当我尝试使用反序列化器时,它给出了一个异常。

{"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[InfluxDB.Serie]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo 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.\r\nPath 'results', line 2, position 12."}

最佳答案

您收到此错误是因为您的 JSON 是分层的,而您的类本质上是扁平的。如果你使用 JSONLint.com验证和重新格式化 JSON,您可以更好地看到结构:

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

这对应于以下类结构(我最初使用 json2csharp.com 生成,然后手动编辑以添加 [JsonProperty] 属性):

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; }
}

您可以将 JSON 反序列化为上述类结构,如下所示:

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

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

关于c# - 反序列化 Json 对象时出现 "because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33427579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com