Skip to content

JsonElement.TryGetProperty()/JsonDocument.TryGetNamedPropertyValue() throws exception if the element is a JsonArray #111845

@DrEsteban

Description

@DrEsteban

Description

This is a fairly minor bug all things considered but...still feels like a bug w.r.t. user expectation.

I have a personal app that accepts JSON payloads and tries to parse things from it. I try to deserialize the incoming string as JsonElement and use TryGetProperty() to see if certain fields are in the payload.

I noticed that TryGetProperty() throws if the JsonElement is an Array instead of an Object. Overall that's fine, and the exception message is intuitive enough, but the general expectation of Try*-type methods is they do not throw and instead simply return false. I know it's not a hard-and-fast "rule", and to be fair the method is documented with /// <exception cref="InvalidOperationException" /> but this seemed like a situation where it was reasonable to expect the call to return false instead of throw. Because the method exists on the "generic" JSON base class JsonElement, which can encapsulate any valid JSON, it feels reasonable to expect non-exceptional behavior from this Try*-type method.

Reproduction Steps

string json = """
	[
	  {
	    "foo": "bar"
	  }
	]
	""";
var obj = JsonSerializer.Deserialize<JsonElement>(json);
obj.TryGetProperty("foo", out var prop);

Expected behavior

false is returned instead of InvalidOperationException thrown. (The Array does not contain a property called "foo" 🙂)

Actual behavior

Throws exception:

The requested operation requires an element of type 'Object', but the target element has type 'Array'.
   at System.Text.Json.ThrowHelper.ThrowJsonElementWrongTypeException(JsonTokenType expectedType, JsonTokenType actualType)
   at System.Text.Json.JsonDocument.TryGetNamedPropertyValue(Int32 index, ReadOnlySpan`1 propertyName, JsonElement& value)
   at System.Text.Json.JsonElement.TryGetProperty(ReadOnlySpan`1 propertyName, JsonElement& value)
   at System.Text.Json.JsonElement.TryGetProperty(String propertyName, JsonElement& value)
   ...

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions