Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

 {
   "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.

like image 561
EResman Avatar asked May 17 '26 00:05

EResman


2 Answers

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.

like image 62
haldo Avatar answered May 18 '26 12:05

haldo


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;
like image 43
Marc Gravell Avatar answered May 18 '26 13:05

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!