问题
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