I want to parse a JSON object with System.Text.Json like this:
[{
"success": {
"/a/b/c": false
}
}]
I want to find out if the first property is named e.g. success or error with the following code:
using (var document = JsonDocument.Parse(test))
{
var root = document.RootElement;
var success = root.EnumerateArray().Current;
Console.WriteLine(success);
}
but somehow I cant get to the success property and most importantly its name.
Your JSON is an array of objects, so to get the name of the first property in the first entry in the array you can combine EnumerateArray() and EnumerateObject() like so:
using var document = JsonDocument.Parse(test);
var names = document.RootElement
.EnumerateArray()
.SelectMany(o => o.EnumerateObject())
.Select(p => p.Name);
var firstName = names.FirstOrDefault();
That being said, the JSON standard defines an object as an unordered set of name/value pairs so you might not want to hardcode your code to check just the first property. The following code checks whether the first object has any property of the required name:
var propertyName = "success";
using var document = JsonDocument.Parse(test);
var hasProperty = document.RootElement
.EnumerateArray()
.Take(1) // Just the first object
.Any(o => o.EnumerateObject().Any(p => p.Name == propertyName));
If you want to check whether any object in the array has the required property, remove the .Take(1).
Demo fiddle here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With