With JsonValueKind.Object
you can use:
value.GetProperty("XXX")
With JsonValueKind.Array
you can use:
value.EnumerateArray().ElementAtOrDefault(2)
But is it also possible to get a specific index without enumerating the array?
The reason is that this is called in a tight loop.
I could read all values and cache them in a dictionary myself, but as I read that System.Text.Json
is specifically made for performance I don't want to allocate unnecessary dictionaries.
Here's an example.
static void Main(string[] args)
{
var json = JsonSerializer.Deserialize<JsonElement>(@"[ ""item1"", ""item2""]");
// (seems) to enumerate the whole object - so slow in loops with large arrays
var test1 = json.EnumerateArray().ElementAtOrDefault(1);
// FIXME: crashes
var test2 = json.GetProperty("1");
// would love to have (return null when not existing - does not enumerate array - dictionary-like performance)
// var test3 = json.GetElementAt("1");
}
Note that
- the actual code is called in a tight loop - it needs close to O(1) performnce
- the array can be quite large (not just two elements)