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

╄→гoц情女王★ 提交于 2021-02-17 02:48:30

问题


I have json that looks like this, the key "123" could be any number.

 {
   "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". How can I do that with System.Text.Json? I'm using .NET Core 3.1.


回答1:


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. Or you just want the first:

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



回答2:


Since one of the json keys can vary ("123"), this can be represented by a Dictionary<>. The following classes model your 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:

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

To access 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.



来源:https://stackoverflow.com/questions/60089463/query-or-deserialize-json-with-dynamic-keys-using-system-text-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!