json.NET抛出InvalidCastException反序列化2D数组 [英] json.NET throwing an InvalidCastException deserializing a 2D array
本文介绍了json.NET抛出InvalidCastException反序列化2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从json字符串反序列化double
值的二维数组.以下代码复制了我的问题:
I'm attempting to deserialize a 2 dimensional array of double
values from a json string. The following code replicates my problem:
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");
两个整数x
和y
具有期望值94
和180
.但是,当执行到达// PROBLEM
行时,会发生以下异常:
The two integers, x
and y
, have the expected values 94
and 180
. But when execution hits the // PROBLEM
line, the following exception occurs:
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.
我应该如何使用json.NET以便不会发生此异常?
array
的期望值应该清楚.
推荐答案
这有效:
JObject obj = JObject.Parse(json);
double[,] array = obj["array2D"].ToObject<double[,]>();
因为,按照@dbc,
差异似乎没有得到很好的记录. JToken.Value 基本上可以一个 Convert.ChangeType 基本类型,而 ToObject()实际上反序列化.
the difference doesn't seem well documented. JToken.Value basically does a Convert.ChangeType which is for primitive types, while ToObject() actually deserializes.
这篇关于json.NET抛出InvalidCastException反序列化2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文