Skip to content

System.Text.Json source generator fails for covariant properties when [JsonIgnore] is specified #63443

Closed

Description

@Kloizdena

Description

I have a class hierarchy where the derived class overrides one of the properties using covariant return type. I want to omit this property from the JSON, so I added [JsonIgnore] attributes to both properties:

public class A
{
	[JsonIgnore]
	public virtual object Id { get; }
}
public class GenericB<T> : A
	where T : class
{
	[JsonIgnore]
	public override T Id { get; }
}

When I try to use the Json source generator for the derived type, it fails. I tried without generics, but it also fails.

Reproduction Steps

Add the following classes to a .NET 6 project and try to build it:

using System.Text.Json.Serialization;

public class A
{
	[JsonIgnore]
	public virtual object Id { get; }
}
public class B : A
{
	[JsonIgnore]
	public override string Id { get; }
}
public class GenericB<T> : A
	where T : class
{
	[JsonIgnore]
	public override T Id { get; }
}

[JsonSerializable(typeof(B))]
[JsonSerializable(typeof(GenericB<string>))]
public partial class Context : JsonSerializerContext
{

}

Expected behavior

The project should build without errors.

Actual behavior

The source generator fails with an error:

Build started...
1>------ Build started: Project: JsonTest, Configuration: Debug Any CPU ------
1>CSC : warning CS8785: Generator 'JsonSourceGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type 'ArgumentException' with message 'An item with the same key has already been added.'
1>C:\src\JsonTest\JsonTest\JsonClasses.cs(22,22,22,29): error CS0534: 'Context' does not implement inherited abstract member 'JsonSerializerContext.GeneratedSerializerOptions.get'
1>C:\src\JsonTest\JsonTest\JsonClasses.cs(22,22,22,29): error CS0534: 'Context' does not implement inherited abstract member 'JsonSerializerContext.GetTypeInfo(Type)'
1>Done building project "JsonTest.csproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Regression?

No response

Known Workarounds

No response

Configuration

.NET 6.0.101
Microsoft Windows [Version 10.0.19044.1415]
x64

Other information

No response

Activity

  1. ghost added
    untriaged
    on Jan 6, 2022
  2. added this to the 7.0.0 milestone on Jan 14, 2022
  3. krwq commented on Jan 14, 2022

    @krwq
    Member

    Agreed this looks incorrect, any chance you'd be interested in contributing a fix?

  4. added and removed
    untriaged
    on Jan 14, 2022
  5. Kloizdena commented on Jan 14, 2022

    @Kloizdena
    ContributorAuthor

    Yes, I can take a look.

  6. Kloizdena commented on Jan 14, 2022

    @Kloizdena
    ContributorAuthor

    The exception is thrown at this line:

    if (propGenSpec.DefaultIgnoreCondition == JsonIgnoreCondition.Always)
    {
    (ignoredMembers ??= new Dictionary<string, PropertyGenerationSpec>()).Add(memberName, propGenSpec);
    }

    Based on this, I tested a similar case and found that the generator runs into the same problem when there is no covariance involved, only property hiding without overriding:

        public class IgnoredBase
        {
            [JsonIgnore]
            public string Id { get; set; }
        }
        public class IgnoredBase_IgnoredDerived : IgnoredBase
        {
            [JsonIgnore]
            public new string Id { get; set; }
        }

    Modifying the Add to TryAdd would solve this issue, but what about other cases when only one of the properties has the [JsonIgnore] attribute?

        public class IgnoredBase
        {
            [JsonIgnore]
            public string Id { get; set; }
        }
    
        public class IgnoredBase_NotIgnoredDerived : IgnoredBase
        {
            public new string Id { get; set; }
        }
    
        public class NotIgnoredBase
        {
            public string Id { get; set; }
        }
        public class NotIgnoredBase_IgnoredDerived : NotIgnoredBase
        {
            [JsonIgnore]
            public new string Id { get; set; }
        }
    
    NotIgnoredBase a = new NotIgnoredBase_IgnoredDerived();
    a.Id = "Test"; // Should be serialized?
    var b = new NotIgnoredBase_IgnoredDerived();
    b.Id = "Test"; // Should be ignored?
    IgnoredBase c = new IgnoredBase_NotIgnoredDerived();
    c.Id = "Test"; // Should be ignored?
    var d = new IgnoredBase_NotIgnoredDerived();
    d.Id = "Test"; // Should be serialized?
  7. added
    source-generator
    on Jan 21, 2022
  8. eiriktsarpalis commented on Jan 24, 2022

    @eiriktsarpalis
    Member

    Slightly related to #59364 which also tracks JsonIgnoreAttribute consistency issues.

  9. eiriktsarpalis commented on Jan 24, 2022

    @eiriktsarpalis
    Member

    More relevant, #50078

  10. krwq commented on May 31, 2022

    @krwq
    Member

    As per #63823 (comment) we need to look at this problem holistically and write down all scenarios and their expected behavior before we start making any fixes

  11. modified the milestones: 7.0.0, Future on Jul 9, 2022
  12. eiriktsarpalis commented on Jun 21, 2023

    @eiriktsarpalis
    Member

    Fixed by #84756

  13. modified the milestones: Future, 8.0.0 on Jun 22, 2023
  14. ghost locked as resolved and limited conversation to collaborators on Jul 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.Jsonbugsource-generator

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions