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() ????;
}
CodePudding user response:
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.
CodePudding user response:
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();