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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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)).
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; }
}

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.