System.Text.Json JsonElement.GetProperty() KeyNotFoundException

Viewed 2020

I' trying the new .net 5 System.Text.Json to analyze a json file now. One of the JsonElement.GetRawText() looks like:

{"name":"filter","in":"query","required":false,"type":"string"}

If I use: (para is the JsonElement)

var eo = para.EnumerateObject();
while (eo.MoveNext())
{
    <div class="col col-4">
        @eo.Current.Name = @eo.Current.Value
    </div>
}

I can see something like "in = header". But if I switch to:

    var paraPosition = para.GetProperty("in");

I will get: KeyNotFoundException: The given key was not present in the dictionary. Did I get something wrong? Thanks for help.

=========================================== More information:

It's in fact a json generated by swagger-doc. The levels are like:

RootElement/get/paths/(many apis listed as properties rather than array)/get/parameters/[para]/in

How I get paths:

        var jsonDocument = GetJsonDocument();
        var elementOfPaths = jsonDocument.RootElement.GetProperty(ApiNode);
        return elementOfPaths;

How I get apis and "get":

var apiElement = Model.Value.EnumerateObject();
@while (apiElement.MoveNext())
{
    var get = apiElement.Current.Value.EnumerateObject();
    get.MoveNext();

so far so good, I can use get.Current.Value.GetProperty("parameters").

How I get parameters and para:

    var parameters = get.Current.Value.GetProperty("parameters");
    <div class ="row">
        @foreach (var para in parameters.EnumerateArray())
        {
            <div>@para.GetRawText()</div>
            var eo = para.EnumerateObject();
            while (eo.MoveNext())
            {
                if (eo.Current.Name != "in")
                {
                    continue;
                }

                var paraClass = eo.Current.Value.GetString() == "header" ? "text-secondary"
                    : eo.Current.Value.GetString() == "query" ? "text-info"
                        : "text-danger";

But now, I cannot use para.GetProperty("in"). Instead, I use EnumerateObject, which is ugly.

Seems it's something about the JsonArray?

1 Answers

Sorry guys, it turned out that it's a mistake of the json file: Not ALL the elements in [parameters] has the "in" property! So one para fails all fails, since they are in the same loop.

Now I changed it to:

    if (para.TryGetProperty("in", out JsonElement paraPosition))
    {
       //...
    }

Everything is fine now.

I think the file was generated by swagger itself. Maybe swagger made the mistake, or some developers of us did. I will check it out.

And I got the inspiration from Panagiotis Kanavos' words "wrong element". Thanks again :)

Related