kdbanman
kdbanman

Reputation: 10557

json.NET throwing an InvalidCastException deserializing a 2D array

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.

Upvotes: 2

Views: 2212

Answers (2)

Stephen Brickner
Stephen Brickner

Reputation: 2602

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.

Upvotes: -1

EZI
EZI

Reputation: 15364

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.

Upvotes: 5

Related Questions