1

I am new to C#. I have the following JSON parsed with newtonsoft:

{"Results":{"output1":{"type":"table","value":{"ColumnNames":["Purchased Bike","Scored Labels"],"ColumnTypes":["String","Double"],"Values":[["value","0.55503808930127"]]}}}}

I want to extract the value 0.555... which is under the "Values" level. I was thinking about converting this JSON to a list and then extracting the last element of that:

var pred = results["Results"]["output1"]["value"]["Values"].ToObject<List<"Values">>();

but List is highlighted as being improper. Note that results is of type Newtonsoft.Json.Linq.JObject.

If I try:

var pred = results["Results"]["output1"]["value"]["Values"].ToObject<List<Values>>();

without quotes, Values is highlighted as being a type or namespace that is not found.

How can I cast the "Values" level of my JSON into a list, and then extract the last item?

Zizzipupp
  • 1,301
  • 1
  • 11
  • 27

1 Answers1

3

Using the VS 2019 Paste JSON as Classes feature, you can easily create a set of classes to match your JSON:

VS 2019 'Paste JSON as Classes' feature

You can then use that as Model classes to parse into, without having to deal with JObject or JArray (which gets more inconvenient the more you want to do with it).

Working demo: see .NET Fiddle -> https://dotnetfiddle.net/o5fIH5

Code from Fiddle:

using System;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        var json = "{\"Results\":{\"output1\":{\"type\":\"table\",\"value\":{\"ColumnNames\":[\"Purchased Bike\",\"Scored Labels\"],\"ColumnTypes\":[\"String\",\"Double\"],\"Values\":[[\"value\",\"0.55503808930127\"]]}}}}";
        var parsed = JsonConvert.DeserializeObject<Rootobject>(json);

        foreach (var array in parsed.Results.output1.value.Values)
            foreach (var entry in array)
                Console.WriteLine(entry);

        Console.WriteLine("\r\nItem Value: " + parsed.Results.output1.value.Values[0][1]);
    }
}

// Generated classes:

public class Rootobject
{
    public Results Results { get; set; }
}

public class Results
{
    public Output1 output1 { get; set; }
}

public class Output1
{
    public string type { get; set; }
    public Value value { get; set; }
}

public class Value
{
    public string[] ColumnNames { get; set; }
    public string[] ColumnTypes { get; set; }
    public string[][] Values { get; set; }
}
Peter B
  • 22,460
  • 5
  • 32
  • 69