kdb*_*man 3 c# arrays json casting json.net
我正在尝试double从json字符串反序列化二维数组的值。以下代码复制了我的问题:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
// Here is the json string I'm deserializing:
string json = @"{
""array2D"": [
[
1.2120107490162675,
-0.05202334010360783,
-0.9376574575207149
],
[
0.03548978958456018,
1.322076093231865,
-4.430964590987738
],
[
6.428633738739363e-05,
-1.6407574756162617e-05,
1.0
]
],
""y"": 180,
""x"": 94
}";
// Here is how I deserialize the string:
JObject obj = JObject.Parse(json);
int x = obj.Value<int>("x");
int y = obj.Value<int>("y");
// PROBLEM: InvalidCastException occurs at this line:
double[,] array = obj.Value<double[,]>("array2D");
Run Code Online (Sandbox Code Playgroud)
这两个整数x和y具有期望的值94和180。但是当执行成功时// PROBLEM,会发生以下异常:
An unhandled exception of type
'System.InvalidCastException'
occurred in Newtonsoft.Json.dll
Additional information:
Cannot cast Newtonsoft.Json.Linq.JArray
to Newtonsoft.Json.Linq.JToken.
Run Code Online (Sandbox Code Playgroud)
我应该如何使用json.NET以便不会发生此异常?
的预期值array应明确。
这有效:
JObject obj = JObject.Parse(json);
double[,] array = obj["array2D"].ToObject<double[,]>();
Run Code Online (Sandbox Code Playgroud)
因为,按照@dbc,
差异似乎没有得到充分证明。JToken.Value基本上执行适用于原始类型的Convert.ChangeType,而ToObject()实际上反序列化。