c# - 为什么下面的 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;
}
}
可能是什么问题,我该如何解决?
解决方案
你可以通过一个临时的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();
推荐阅读
- javascript - 使 Django-leaflet 弹出窗口始终打开以显示 django-geojson 功能属性
- docker - 连接过程中出错:获取 http://docker:2375/v1.24/containers/json: dial tcp: lookup docker on 10.0.2.3:53: server misbehaving
- c - 如何有效地在字符串指针的特定位置插入字符?
- ios - 搜索 Tableview 时如何显示子响应?
- r - 使用 ggplot2 或在 R 中绘图创建子弹图
- algorithm - 超出算法时间限制
- python - 如何用多个条件替换列值
- python - 简单 Keras ANN MNIST 数据集中的错误
- discord.js - 用户发送消息时如何添加角色
- apache-beam - 如何使用 apache_beam 将 csv 文件数据从 VM 系统写入 pub/sub?