How to get a Json property name of a JsonObject when using System.Text.Json.Nodes namespace in .NET 6?

Viewed 265

I have a simple Json string

{
    "property1": "value1",
    "property2": "value1"
}

that I parse to a JsonObject using the System.Text.Json.Nodes namespace with the following line

JsonObject obj = JsonNode.Parse(requestBody).AsObject();

How can I get the properties names (property1 and property2) of the JsonObject?

If there are alternatives, It would help me

1 Answers

you can try this

JsonObject obj = JsonNode.Parse(requestBody).AsObject();
string[] propertyNames = obj.Select(p =>p.Key ).ToArray();

result

["property1","property2"]

or

   var doc = JsonDocument.Parse(json);

    foreach (var property in doc.RootElement.EnumerateObject())
    {
        Console.WriteLine($"{property.Name} - {property.Value}");
    }

result

property1 - value1
property2 - value1

or using linq

string[] propertyNames = doc.EnumerateObject().Select(p => p.Name ).ToArray();
Related