【发布时间】:2015-10-17 23:41:17
【问题描述】:
我正在尝试从 json 字符串中反序列化 double 值的二维数组。以下代码复制了我的问题:
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 行时,会出现以下异常:
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 的期望值应该明确。
【问题讨论】:
标签: c# arrays json casting json.net