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

[Bug]: Default ObjectToInferredTypesConverter causes TypeDiscriminator property to be missing in top-level types for polymorphic JSON Serialization #1763

Open
Greenscreener opened this issue Jul 24, 2024 · 1 comment
Labels

Comments

@Greenscreener
Copy link

Describe the bug 🐞

When using the SystemTextJsonContentSerializer with default JsonSerializerOptions including the ObjectToInferredTypesConverter, TypeDiscriminator properties used in Polymorphic JSON Serialization are ignored in first-level objects, even though nested types receive their TypeDiscriminator properties correctly.

Step to reproduce

  1. Use the default SystemTextJsonContentSerializer with default configuration.
  2. Create a type with a polymorphic serilaization configiuration, for instance:
    [JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
    [JsonDerivedType(typeof(UserIdentifier), typeDiscriminator: "m.id.user")]
    [JsonDerivedType(typeof(PhoneIdentifier), typeDiscriminator: "m.id.phone")]
    [JsonDerivedType(typeof(ThirdpartyIdentifier), typeDiscriminator: "m.id.thirdparty")]
    public abstract record Identifier();
    public record UserIdentifier(string user) : Identifier();
    public record PhoneIdentifier(string country, string phone) : Identifier();
    public record ThirdpartyIdentifier(string medium, string address) : Identifier();
  3. Try to send such a type using a Post method, it gets serialized correctly but the TypeDiscriminator property is ignored.

Reproduction repository

No response

Expected behavior

TypeDiscriminator property should be present

Screenshots 🖼️

No response

IDE

No response

Operating system

No response

Version

No response

Device

No response

Refit Version

No response

Additional information ℹ️

No response

@etiennelepagel
Copy link

Hey @Greenscreener,

You can use this:

var jsonSerializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
    PropertyNameCaseInsensitive = true
};

this._targetsProvider = RestService.For<IMyClient>(
    this.HttpClient,
    new RefitSettings { ContentSerializer = new SystemTextJsonContentSerializer(jsonSerializerOptions) });

In my case PropertyNameCaseInsensitive = true was essential to deserialize the response, but the type descriminator is still there without it.

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

No branches or pull requests

2 participants