为什么以下 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);

在以上之后,coord 的值为:{0;0;0}

下面是 D3Point 类。

public readonly struct D3Point : IEquatable<D3Point>
{
  public static readonly D3Point Null = new D3Point(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;
  }
}

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

yang01104891 回答:为什么以下 JSON 没有正确反序列化?

您可以通过 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["Z"]).First();
本文链接:https://www.f2er.com/10889.html

大家都在问