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

Query or deserialize json with dynamic keys using 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。

类似于:

public class Rootobject
{
    public string key1 { get; set; }
    public InnerObject key2 { get; set; }
}

public class InnerObject 
{
    public Dictionary<string, ObjectTheThird> items { get; set; }
        = new Dictionary<string, ObjectTheThird>();
}

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

并使用 Dictionary<,> 上的 API 查看项目。或者你只想要第一个:

var name = obj.key2.items.First().Value.name;

由于 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

注意,我给 类 命名很快...请考虑给 类 更好的名字,更具描述性的名字。