System.Text.Json - How to Validate Discriminator Field Presence for Derived Classes during Deserialization #104089
Unanswered
mstfgueclue
asked this question in
Q&A
Replies: 1 comment
-
Hi, the only mechanism available today is to mark the base type as abstract, if possible. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello,
I am working on a project using
System.Text.Json
for handling polymorphic deserialization and I've encountered a challenge with validating the presence of the discriminator field ($type
) before deserialization completes.Context:
My application uses a base class
NotificationDto
with several derived types (likeEmailNotificationDto
andSmsNotificationDto
). The type of derived class to instantiate is determined by a$type
discriminator field in the JSON payload. However, .NET resolves this field internally and by the time deserialization completes, if the$type
field is missing, the object automatically falls back to being deserialized as the base type. Consequently, I can't access the$type
field for further validation (e.g., in FluentValidation), which prevents me from correctly identifying and handling the derived types post-deserialization.Here's a JSON structure example:
In the above JSON, if the
$type
field is missing, the type falls back to the base type, which is not ideal for my use case. I'm aware that one solution could involve adding a dedicated property in the DTO to mirror the$type
field and validate its presence, but I'm curious if there's a way to handle this entirely withinSystem.Text.Json
attributes or through configuration.Question:
Is there a mechanism in
System.Text.Json
to enforce the presence of the$type
discriminator in the JSON before falling back to a base type during deserialization? I'd prefer to handle this directly in the library's deserialization process rather than adding workaround properties in my DTOs. It would be really nice having an option likeIgnoreMissingTypeDiscriminator
Any suggestions or best practices on how to achieve this with
System.Text.Json
?Thanks for any insights you can provide!
microsoft docs about serialization of polymorphic types: here
Beta Was this translation helpful? Give feedback.
All reactions