Skip to content

Contract model example is incorrect - Field DerivedTypes cannot be set #45871

@kezenator

Description

@kezenator

Type of issue

Code doesn't work

Description

The example in the "Configure polymorphism with the contract model" section is incorrect.
It suggest that you need to set the "DerivedTypes" property initialization - but property JsonPolymorphismOptions.DerivedTypes is get only.

Instead of:

jsonTypeInfo.PolymorphismOptions = new JsonPolymorphismOptions
{
    TypeDiscriminatorPropertyName = "$point-type",
    IgnoreUnrecognizedTypeDiscriminators = true,
    UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FailSerialization,
    DerivedTypes =
    {
        new JsonDerivedType(typeof(ThreeDimensionalPoint), "3d"),
        new JsonDerivedType(typeof(FourDimensionalPoint), "4d")
    }
};

It should be:

jsonTypeInfo.PolymorphismOptions = new JsonPolymorphismOptions
{
    TypeDiscriminatorPropertyName = "$point-type",
    IgnoreUnrecognizedTypeDiscriminators = true,
    UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FailSerialization
};
jsonTypeInfo.PolymorphismOptions.DerivedTypes.Add(new JsonDerivedType(typeof(ThreeDimensionalPoint), "3d"));
jsonTypeInfo.PolymorphismOptions.DerivedTypes.Add(new JsonDerivedType(typeof(FourDimensionalPoint), "4d"));

Page URL

https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/polymorphism

Content source URL

https://github.com/dotnet/docs/blob/main/docs/standard/serialization/system-text-json/polymorphism.md

Document Version Independent Id

17511810-6572-ad88-6eaf-4f9bded720b7

Platform Id

c3675880-a4e2-ce92-63f1-ddab72bb3c4c

Article author

@gewarren

Metadata

  • ID: 179cc49a-a37d-155e-5ecf-deca4f219a5a
  • PlatformId: c3675880-a4e2-ce92-63f1-ddab72bb3c4c
  • Service: dotnet-fundamentals

Related Issues

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions