0

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"?

dbc
  • 104,963
  • 20
  • 228
  • 340

2 Answers2

1

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.

Lior
  • 508
  • 3
  • 18
  • If you don't know the exact shape of the `result` property (and if it may change), you could also use a `JsonElement` property to capture the "rest" of the JSON. Then you can iterate over that (like any other document object model (DOM)). – ahsonkhan Feb 19 '20 at 03:11
1

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; }
}
Innat3
  • 3,561
  • 2
  • 11
  • 29
  • You can also use Visual Studio to generate the class. In VS, Edit > Paste Special > Paste JSON as Classes. In this case, the `count` will be string, and not int. – ahsonkhan Feb 19 '20 at 03:09