首页 > 解决方案 > 为什么下面的 JSON 不能正确反序列化?

问题描述

在尝试将简单的 json 反序列化为类型的对象时,我遇到了一个相当奇怪的问题,该对象D3Point从 NuGet 包中使用。

json 看起来像这样:

string cJson = face["Edges"][0]["Coords"][0].ToString();
"{\"X\": 1262.6051066219518, \"Y\": -25972.229375190014, \"Z\": -299.99999999999994}"

以及反序列化尝试:

D3Point coord = JsonConvert.DeserializeObject<D3Point>(cJson);

在上述之后,坐标的值是:{0;0;0}.

下面是D3Point课堂。

public readonly struct D3Point : IEquatable<D3Point>
{
  public static readonly D3Point Null = new D3Point(0, 0, 0);

  public double X { get; }
  public double Y { get; }
  public double Z { get; }

  public D3Point(double coordinateX, double coordinateY, double coordinateZ)
  {
      this.x = coordinateX; 
      this.y = coordinateY;
      this.z = coordinateZ;
  }
}

可能是什么问题,我该如何解决?

标签: c#jsonserializationdeserialization

解决方案


你可以通过一个临时的Dictionary<string, double>

//local or method
D3Point toD3Point(string json) { 
  var j = JsonConvert.DeserializeObject<Dictionary<string, double>>(json); 
  return new D3Point(j["X"],j["Y"],j["Z"]);
}
        
D3Point coord = toD3Point(cJson);

如果你真的想单行,使用 LINQ 有点讨厌,但是..

new[]{ JsonConvert.DeserializeObject<Dictionary<string, double>>(cJson) }.Select(j => new D3Point(j["X"],j["Y"],j["Z"]).First();

推荐阅读