Steve Webb
Steve Webb

Reputation: 19

Access nested values in json using System.Text.Json

I have a JSON file returned from a system that looks like this:

{
    "value1": "Hello",
    "value2": "World",
    "result":
    {
        "stats":
        {
            "count":"1"
        }
    }
}

Getting to the values "Value1" and "Value2" is no issue. However, I cannot get to "count" - Does not appear to be in a good format.

This is my code:

class Program
{
    static void Main(string[] args)
    {
        string json1 = File.ReadAllText("test.json");
        var info = JsonSerializer.Deserialize<SnData>(json1);
        WriteLine("Value1: {0} , Value2: {1}",info.value1,info.value2);
    }
}
class SnData
{
    public string value1 {get; set;}
    public string value2 {get; set;}  
}

How to get the value "count"?

Upvotes: 0

Views: 354

Answers (2)

Innat3
Innat3

Reputation: 3576

The simplest way would be to replicate the structure of your json. There are handy websites that can do this for you such as http://json2csharp.com/

class SnData
{
    public string value1 { get; set; }
    public string value2 { get; set; }
    public Result result { get; set; }
}

class Result
{
    public Stats stats { get; set; }
}

class Stats
{
    public int count { get; set; }
}

Upvotes: 1

Lior
Lior

Reputation: 508

You can fetch the count with the following code:

public class SnData
{
    public string Value1 { get; set; }
    public string Value2 { get; set; }
    public Result Result { get; set; }

}
public class Result
{
    public Stats Stats { get; set; }

}

public class Stats
{
    public int Count { get; set; }
}

In the main:

 class Program
{
    static void Main(string[] args)
    {
        string json1 = File.ReadAllText("test.json");
        var info = JsonSerializer.Deserialize<SnData>(json1);
        WriteLine("Value1: {0} , Value2: {1}, Count {2}", info.Value1, info.Value2, info.Result.Stats.Count);
    }
}

The above code will simply replicate the json structure.

Upvotes: 1

Related Questions