简体   繁体   English

使用 System.Text.Json 访问 json 中的嵌套值

[英]Access nested values in json using System.Text.Json

I have a JSON file returned from a system that looks like this:我有一个从系统返回的 JSON 文件,如下所示:

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

Getting to the values "Value1" and "Value2" is no issue.获取值“Value1”和“Value2”是没有问题的。 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"?如何获得值“计数”?

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.上面的代码将简单地复制 json 结构。

The simplest way would be to replicate the structure of your json.最简单的方法是复制 json 的结构。 There are handy websites that can do this for you such as http://json2csharp.com/有一些方便的网站可以为您执行此操作,例如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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM