Skip to content
This repository was archived by the owner on Mar 26, 2025. It is now read-only.
This repository was archived by the owner on Mar 26, 2025. It is now read-only.

Duplicate Key if several type have the same discriminator #113

Open
@Itori

Description

@Itori

If 2 types have the same discriminator, you will get a duplicate key error.

For reproduction add to DiscrinatorTests :

    public class BaseObjectResponse
    {
        public int Id { get; set; }
    }

    [JsonDiscriminator(12)]
    public class NameObjectResponse : BaseObjectResponse
    {
        public string Name { get; set; }
    }
        [Theory]
        [InlineData(DiscriminatorPolicy.Default, @"{""BaseObject"":{""$type"":12,""Name"":""foo"",""Id"":1},""NameObject"":{""Name"":""bar"",""Id"":2}}")]
        [InlineData(DiscriminatorPolicy.Auto, @"{""BaseObject"":{""$type"":12,""Name"":""foo"",""Id"":1},""NameObject"":{""Name"":""bar"",""Id"":2}}")]
        [InlineData(DiscriminatorPolicy.Never, @"{""BaseObject"":{""Name"":""foo"",""Id"":1},""NameObject"":{""Name"":""bar"",""Id"":2}}")]
        [InlineData(DiscriminatorPolicy.Always, @"{""BaseObject"":{""$type"":12,""Name"":""foo"",""Id"":1},""NameObject"":{""$type"":12,""Name"":""bar"",""Id"":2}}")]
        public void WritePolymorphicObjectDuplicateKey(DiscriminatorPolicy discriminatorPolicy, string expected)
        {
            JsonSerializerOptions options = new JsonSerializerOptions();
            options.SetupExtensions();
            DiscriminatorConventionRegistry registry = options.GetDiscriminatorConventionRegistry();
            registry.ClearConventions();
            registry.RegisterConvention(new DefaultDiscriminatorConvention<int>(options));
            registry.RegisterType<NameObject>();
            registry.RegisterType<NameObjectResponse>();
            registry.DiscriminatorPolicy = discriminatorPolicy;

            BaseObjectHolder obj = new BaseObjectHolder
            {
                BaseObject = new NameObject
                {
                    Id = 1,
                    Name = "foo"
                },
                NameObject = new NameObject
                {
                    Id = 2,
                    Name = "bar"
                }
            };

            string actual = JsonSerializer.Serialize(obj, options);

            Assert.Equal(expected, actual);
        }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions