c# - 使用 System.Text.Json 使用动态键查询或反序列化 json

标签 c# .net json .net-core system.text.json

我有看起来像这样的 json,键“123”可以是任何数字。

 {
   "key1": "",
   "key2": {
      "items": {
         "123": {
            "pageid": 123,
            "name": "data"
         }
      }
    }
 }

我想用 System.Text.Json 反序列化或查询 json,这样我就可以获得键“name”的值。我如何使用 System.Text.Json 做到这一点?我正在使用 .NET Core 3.1。

最佳答案

由于其中一个 json 键可能不同 ( "123" ),因此可以用 Dictionary<> 表示.以下类为您的 json 建模。

public class ItemProps
{
    public int pageid { get; set; }
    public string name { get; set; }
}

public class Item
{
    public Dictionary<string, ItemProps> items { get; set; }
}

public class Root
{
    public string key1 { get; set; }
    public Item key2 { get; set; }
}

然后使用 System.Text.Json 反序列化你会使用:

var data = JsonSerializer.Deserialize<Root>(json);

访问name :

var name = data.key2.items["123"].name

Try it online

请注意,我快速命名了类...请考虑为类提供更好的名称,更具描述性的名称。

关于c# - 使用 System.Text.Json 使用动态键查询或反序列化 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60089463/

相关文章:

c# - 强制下载文件,默认不在浏览器上打开它

c# - 使用 Json.Net 仅序列化选定的属性

php - 如何从外部数组获取内部数组

c# - 光谱流 : generate tests with underscore between words

c# - WPF 中的文件选择器对话框在哪里?

c# - DrawingImage 样式绑定(bind)错误

c# - 如何使 TreeView 和 ListBox 的 SelectedItem 保持同步?

c# - 在 C# 中清除 ColorConvertedBitmap

json - 实现实体组件系统的最佳方式是什么

c# - 在类和接口(interface)之间进行选择