c# - 反序列化对象时出错

标签 c# json json.net

我有一个 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/

相关文章:

c# - 我可以在 Xamarin、C#、iOS 中保存对象数组(或 json 数组、字典数组)吗?

c# - 使用 Moq 时出现奇怪的 "Object reference not set to an instance of an object"错误

c# - 在 Unity 中使用反射注册通用类型

javascript - 如何在单选按钮单击时获取 json 存储的数据

android - 改造 Android : java. lang.IllegalStateException:应为 BEGIN_ARRAY 但在第 1 行第 2 列路径中为 BEGIN_OBJECT

c# - 使用 JsonConverter 序列化/反序列化各种 `Brush` 类型

c# - Ultra Numeric Editor 仅将默认设置为最多 2 位小数

ios - 解析 JSON "Unescaped control character around character 981"时出错

java - 将 Jackson JSON 对象引用转换为 JSON.Net 对象引用

C# JSON.Net 将一个列表中的项目放入另一个列表中