charL
charL

Reputation: 399

Get Property Name from JSON

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.

Upvotes: 3

Views: 11195

Answers (2)

Michael Schönbauer
Michael Schönbauer

Reputation: 1001

Maybe this helps

you gotta move that enumerator, (you gotta move that color teehveeeeeyyy....)

class Program
{
    static void Main(string[] args)
    {
        string json = "[{\"success\": {\"/a/b/c\": false}}]";
        using (var document = JsonDocument.Parse(json))
        {
            var root = document.RootElement;
            var enumerator = root.EnumerateArray();
            while (enumerator.MoveNext())
            {
                Console.WriteLine($"You are now at array element {enumerator.Current}");

                var elementContentEnumerator = enumerator.Current.EnumerateObject();
                while (elementContentEnumerator.MoveNext())
                {
                    Console.WriteLine($"You are now at property {elementContentEnumerator.Current.Name}");
                }

            }
            Console.ReadLine();
        }
    }
}

Also: Things to consider when manually parsing through JSONS

There are a lot of powerful JSON Frameworks available for C#. And there are lot of things available, to make the code more fluent. Especially LINQ, which means Language Integrated Query. Have a shot at it. Most of this make working with JSONS and C# really convenient, etc.

So normally (unless it is a very special thing you are up to) you can say that, whenever you are manually parsing through a JSON, and manually looping through enumerators, like in the code above, you are probably not leveraging the full power of C# and it's libraries.

Please accept as answer when it did help,

Greetings, Mike

Upvotes: 0

dbc
dbc

Reputation: 117275

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.

Upvotes: 5

Related Questions