Skip to content

Should we remove DynamicallyAccessedMembers attributes on JsonSerializer? #52268

Closed
@eerhardt

Description

@eerhardt

In 5.0, we annotated the JsonSerializer APIs with DynamicallyAccessedMembers attributes in #38595.

[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
public static TValue? Deserialize<[DynamicallyAccessedMembers(JsonHelpers.MembersAccessedOnRead)] TValue>(string json, JsonSerializerOptions? options = null)

[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
public static string Serialize<[DynamicallyAccessedMembers(MembersAccessedOnWrite)] TValue>(TValue value, JsonSerializerOptions? options = null)

In 6.0, we resolved all the ILLink warnings in System.Text.Json in #51886, which caused us to also add the RequiresUnreferencedCode attributes. This is because the trim annotations can't model everything that needs to be preserved to make these APIs trim compatible. For example, see dotnet/linker#1087.

Having both sets of attributes on these APIs isn't really ideal. The DynamicallyAccessedMembers attributes will only preserve members on the top-level type. So having the DynamicallyAccessedMembers gives a false sense of hope that this API will work with trimming, when in reality it won't.

The small benefit it does provide is in the case where the user is not serializing a graph, but just a class with primitive properties. However, even in this case, we'd like the user to move to use the source generator instead. So keeping these attributes for this tiny case doesn't seem to outweigh the benefit of the encouragement to move to using the source generator.

We also didn't annotate the DataContractSerializer and XmlSerializer APIs like this. We just marked the unsafe APIs with RequiresUnreferencedCode.

However, if we have plans for making the non-source generation Json serializer APIs work with trimming in 6.0, it might not be worth the effort of removing these attributes now, just to add them back in the near future.

cc @vitek-karas @agocke @layomia @steveharter

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions