Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JsonPolymorphic DTOs generated with the openapi2tsclient can't be deserialized #5060

Open
PeterBenko opened this issue Nov 28, 2024 · 0 comments

Comments

@PeterBenko
Copy link

PeterBenko commented Nov 28, 2024

Describe the bug

System.Text.Json based polymorphic C# DTOs that are annotated with

[JsonPolymorphic]
[JsonDerivedType(typeof(SubClass1), "Descriminator1")]
[JsonDerivedType(typeof(SubClass2), "Descriminator2")]
public class SuperClass {
    ...
}

and then generated for TypeScript by $(NSwagExe_Net80) openapi2tsclient don't follow Microsoft's expectations. This is because the generated inherintance toJSON code adds the descriminator in the super class, which gets called after serializing all the fields of the subclass. This results in the descriminator not being the first field, resulting in the following error when trying to send the DTO to the API:

"errors": {
        "superClassParameterDto": [
            "The superClassParameterDto field is required."
        ],
        "$.$type": [
            "The metadata property is either not supported by the type or is not the first property in the deserialized JSON object. Path: $.$type | LineNumber: 0 | BytePositionInLine: 9286."
        ]
},

Version used

"NSwag.MSBuild": {
    "type": "CentralTransitive",
    "requested": "[14.2.0, )",
    "resolved": "14.2.0",
    "contentHash": "KqF8VT+67XBAQSKOV36vsXwvtkcWfJHnyVY8+muDhC2R7uV4wh0/LGQului+exKfvDfySADl48QT+wQnjsgRAg=="
},

To Reproduce

Create a TypeScript client as described above, with polymorphic DTOs where the subclasses have own, different fields. Try to use the API that accepts the super class.

Expected behavior

The generated DTOs should have the discriminator as the first field.

Additional context

We've implemented a workaround to 'overrides' and wraps the generated TS DTOs' .toJSON() method so that it first creates the descriminator field before calling the oroginal .toJSON(). A data['$type'] = ''; is enough, it just needs to be there first and will be properly filled out by the generated code later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant