3

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.

dbc
  • 104,963
  • 20
  • 228
  • 340
EResman
  • 394
  • 1
  • 5
  • 14

2 Answers2

3

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.

haldo
  • 14,512
  • 5
  • 46
  • 52
2

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;
dbc
  • 104,963
  • 20
  • 228
  • 340
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • System.Text.Json won't populate the `items` dictionary unless the property has public setters and getters. (In .NET 5 the setter can be private if the property is marked with `[JsonInclude]`). See https://dotnetfiddle.net/AMq4ac vs https://dotnetfiddle.net/6PIuSG – dbc Feb 01 '21 at 17:58