json.NET throwing an InvalidCastException deserializing a 2D array

半世苍凉 提交于 2019-12-10 19:05:28

问题


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");

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.

How should I use json.NET so that this exception doesn't occur?

The expected value of array should be clear.


回答1:


This works:

JObject obj = JObject.Parse(json);
double[,] array = obj["array2D"].ToObject<double[,]>();

because, as per @dbc,

the difference doesn't seem well documented. JToken.Value basically does a Convert.ChangeType which is for primitive types, while ToObject() actually deserializes.




回答2:


You can do something like this:

JObject j = JObject.Parse(json);
var list = j.SelectToken("array2D").ToString();
var data = JsonConvert.DeserializeObject<double[,]>(list);

This line:

JObject j = JObject.Parse(json);

does not deserialize the data, it simply parses it to an Object. You still need to tell JSON.NET what type of object you want it serialized to.



来源:https://stackoverflow.com/questions/31658994/json-net-throwing-an-invalidcastexception-deserializing-a-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!