jhoepken
jhoepken

Reputation: 1858

Read List<double> from Json via Newtonsoft in C#

I would like to read a JSON string via the Newtonsoft Json library. It works fine for any basic datatype, but it does not work for a List<double> or any List for that matter.

The test application looks like the following:

static void main()
{
  string jsonString = @"
            {
                'name': 'set1',
                'Xvv': {
                         'parameter': 'hByT',
                         'values': '[1,2,3]'
                    }
            }";
  JObject Json = JObject.Parse(jsonString);

  var name = Json["name"].ToString();
  var data = Json["Xvv"]["values"].Value<List<double> >(); // Raises error
}

The last line throws the following exception:

System.InvalidCastException: Invalid cast from 'System.String' to 'System.Collections.Generic.List

Is there a way to access the data directly as a List<double>?

Upvotes: 1

Views: 472

Answers (1)

Paul Kertscher
Paul Kertscher

Reputation: 9713

In the example JSON you've provided, values is a string. A proper JSON array would be

'values': [1,2,3]

Anyway, after changing the string to the array, .Value<List<double>>() would throw an exception, that a JArray cannot be cast to a JToken - unfortunately I do not really know, why it does not work.

However, JToken.ToObject<T> does the trick, it

Creates an instance of the specified .NET type from the JToken

(see the documentation for ToObject)

With the line

var data = Json["Xvv"]["values"].ToObject<List<double>>();

you can cast the array correctly.

If an IEnumerable would be fine for you, too, you could also use

var data = Json["Xvv"]["values"].Values<double>();

Upvotes: 1

Related Questions