我有一个 JSON 字符串。
[
{
"target":"FDOL00001",
"datapoints":[
{
"y":72.564,
"x":1523858700
}
]
},
{
"target":"FDOL00001",
"datapoints":[
{
"y":86.366,
"x":1523858700
}
]
},
{
"target":"FDOL00001",
"datapoints":[
{
"y":73.90195818815343,
"x":1523858700
}
]
}
]
我正在尝试将其反序列化为一个集合。但是我收到一个错误。有人可以指导我解决此问题的正确方法吗?
class datapoint
{
[JsonProperty("x")]
public int x { get; set; }
[JsonProperty("y")]
public decimal y { get; set; }
}
class jsonMapper
{
[JsonProperty("target")]
public string target { get; set; }
[JsonProperty("datapoints")]
public datapoint datapoints { get; set; }
}
我正在尝试使用以下代码进行转换。
var json = JsonConvert.DeserializeObject<List<jsonMapper>>(objText);
我得到的错误是
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ISSPortal2.datapoint' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\r\nPath '[0].datapoints', line 1, position 40.
我已经查过了this .但它不起作用。 我的代码有什么问题。请帮我识别一下。提前致谢:)
最佳答案
您正在尝试将数组 datapoint[]
反序列化为 datapoint
。
改变
public datapoint datapoints { get; set; }
到
public datapoint[] datapoints { get; set; }
奖励:C# 命名约定,建议您在公共(public)属性中使用大写字母。
class Datapoint
{
[JsonProperty("x")]
public int X { get; set; }
[JsonProperty("y")]
public decimal Y { get; set; }
}
class JsonMapper
{
[JsonProperty("target")]
public string Target { get; set; }
[JsonProperty("datapoints")]
public Datapoint Datapoints { get; set; }
}
关于c# - 反序列化对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49895597/