-1

I have a class written for ProblemDetails. I switched from NewtonSoft to System.Text.Json. I am trying to get the list of "errors", which is a deserialized into the Extensions property, which is decorated with [JsonExtensionData].

I cannot figure out how to enumerate and read the "errors", which inevitable is a dictionary.

I get to the point where I can get the "errors" back a JsonElement, but from JsonElement there is not "j.GetJsonElement", just j.GetString(), j.GetInt(), etc.

How do I get the elements below "errors"?

    [Fact]
    public void DeserializeTest()
    {
        var json = "{\"type\":\"https://tools.ietf.org/html/rfc7231#section-6.5.1\",\"title\":\"One or more validation errors occurred.\",\"status\":400,\"traceId\":\"00-ccf1398eea1494aef2e3fa0f07a34899-09a93c2176a88981-00\",\"errors\":{\"BottomRightX\":[\"Bottom Right X must be greater than Top Left X.\"],\"BottomRightY\":[\"Bottom Right Y must be greater than Top Left Y.\"]}}";

        var problemDetails = JsonSerializer.Deserialize<ProblemDetails>(json);

       problemDetails.Should().NotBeNull();
       problemDetails.Title.Should().NotBeNullOrEmpty();
       problemDetails.Status.Should().Be(400);
       problemDetails.Extensions.Should().NotBeNullOrEmpty();
       var j = problemDetails.Extensions.Should().ContainKey("errors").WhoseValue;
       j.ValueKind.Should().Be(JsonValueKind.Object);

       // all above pass



       var x = j.GetJsonElement() ????;
    }
Tim Bassett
  • 1,325
  • 1
  • 12
  • 23
  • What `ProblemDetails` is? – Guru Stron May 19 '22 at 18:11
  • Ever solve this? I added my own custom `ApiExceptionDetails[]` object to extensions, but then reading it, I simply get a JsonElement with `ValueKind = Array`. I see the string representation in the VS Code debugger, but I can't figure out how to access it. – Terry Mar 13 '23 at 23:29

2 Answers2

0

My best guest is you can create a customer deserialization and in the errors value include a property type, to use it in as part as the custom serialization. But its not recommended. If U can never use object in Json Serialization, only Strong Type Objects to avoid this kind situation.

0

At this moment you should expect either some value or a property. To process properties - use GetProperty/TryGetProperty which has out parameter of JElement type:

j.TryGetProperty("BottomRightY", out JElement bottomRightY).Should().BeTrue();
Guru Stron
  • 102,774
  • 10
  • 95
  • 132