简体   繁体   English

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

[英]Query or deserialize json with dynamic keys using System.Text.Json

I have json that looks like this, the key "123" could be any number.我有一个看起来像这样的 json,键“123”可以是任何数字。

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

I want to deserialize or query the json with System.Text.Json so i can get the value of the key "name".我想用 System.Text.Json 反序列化或查询 json,这样我就可以获得键“name”的值。 How can I do that with System.Text.Json?我怎么能用 System.Text.Json 做到这一点? I'm using .NET Core 3.1.我正在使用 .NET Core 3.1。

Since one of the json keys can vary ( "123" ), this can be represented by a Dictionary<> .由于 json 键之一可能会有所不同( "123" ),因此这可以由Dictionary<> The following classes model your json.以下类为您的 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; }
}

Then to deserialize using System.Text.Json you would use:然后使用System.Text.Json反序列化,您将使用:

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

To access name :访问name

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

Try it online网上试试

Note, I named the classes quickly... please consider giving the classes better names, more descriptive names.请注意,我很快为这些类命名了……请考虑为这些类提供更好的名称,更具描述性的名称。

Something like:就像是:

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

and use the APIs on Dictionary<,> to look at the items.并使用Dictionary<,>上的 API 来查看项目。 Or you just want the first:或者你只想要第一个:

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

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

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