为什么以下 JSON 不能正确反序列化?
Why does the following JSON not deserialize properly?
我在尝试将简单的 json 反序列化为从 NuGet 包中使用的 D3Point
类型的对象时遇到了一个相当奇怪的问题。
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
class.
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;
}
}
可能是什么问题,我该如何解决?
您可以通过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();
我在尝试将简单的 json 反序列化为从 NuGet 包中使用的 D3Point
类型的对象时遇到了一个相当奇怪的问题。
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
class.
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;
}
}
可能是什么问题,我该如何解决?
您可以通过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();