Skip to content

Add JsonContent.Create overloads that accept JsonTypeInfo. #51544

Closed

Description

@layomia

EDIT New proposal can be found here: #51544 (comment)

Details

Background

The existing JsonContent type in System.Net.Http.Json uses existing JsonSerializerOptions-based JsonSerializer.Serialize(Async) overloads which root reflection code and all built-in STJ converters (even when not needed in an app). We should add a new type that uses new JsonSerializerContext-based overloads, which are AOT-friendly and allow for a smaller app. Also the existing type has been marked as "requires unreferenced code", so it is beneficial to provide an alternative which is trim-friendly.

API Proposal

public sealed partial class JsonContent<TValue> : HttpContent
{
  internal JsonContent() { }
  public TValue? Value { get { throw null; } }
}

We should also expose static Create methods for these types to the existing JsonContent :

public sealed partial class JsonContent : HttpContent
{
  // Existing
  // internal JsonContent() { }
  // public Type ObjectType { get { throw null; } }
  // public object? Value { get { throw null; } }
  // public static JsonContent Create(object? inputValue, Type inputType, MediaTypeHeaderValue? mediaType = null, JsonSerializerOptions? options = null) { throw null; }
  // public static JsonContent Create<T>(T inputValue, MediaTypeHeaderValue? mediaType = null, JsonSerializerOptions? options = null) { throw null; }

  // New create methods for JsonContent<TValue>
  public static JsonContent<object?> Create(object? inputValue, Type inputType, JsonSerializerContext context, MediaTypeHeaderValue? mediaType = null) { throw null; }
  public static JsonContent<TValue> Create(TValue? inputValue, JsonTypeInfo<TValue> jsonTypeInfo, MediaTypeHeaderValue? mediaType = null) { throw null; }
}

The new create methods should go on JsonContent - if we put them on JsonContent<TValue>, then it will be possible for users to write awkward code like this:

JsonContent<object> content = JsonContent<int>.Create(myVal, type, context);

Usage

Just like the existing JsonContent type, JsonContent<TValue> can be used when building a HttpResponseMessage based on JSON. The difference is that now the JSON will be serialized in a trim-safe way which is also optimized for app size:

public static Task<HttpResponseMessage> PutAsJsonAsync<TValue>(this HttpClient client, string? requestUri, TValue value, JsonTypeInfo<TValue> jsonTypeInfo, CancellationToken cancellationToken = default)
{
  if (client == null)
  {
      throw new ArgumentNullException(nameof(client));
  }

  JsonContent<TValue> content = JsonContent.Create(value, jsonTypeInfo);
  return client.PutAsync(requestUri, content, cancellationToken);
}

Q/A

Can JsonContent<TValue> derive from JsonContent<T>?

It's better not to do this, because the ILLinker won't be able to trim away reflection-based code and extra JsonConverters used by the existing JsonContent type. The underlying infrastructure for serializing the JSON content is based on overriding virtual methods. Making the new JsonContent<TValue> type derive from the existing type is bad because the linker will preserve the virtual and override methods of called methods in the hierarchy, because it doesn't know which one will be called at run-time. This is discussed in more detail here.

Activity

  1. added this to the 6.0.0 milestone on Apr 20, 2021
  2. self-assigned this
    on Apr 20, 2021
  3. ghost added
    untriaged
    on Apr 20, 2021
  4. removed
    untriaged
    on Apr 20, 2021
  5. changed the title [-]Implement HttpClientJsonExtensions Post/Put methods and JsonContent Create methods that take JSON serialization metadata[/-] [+]Provide JsonContent<T> type that uses pre-generated serialization metadata[/+] on Apr 30, 2021
  6. added
    api-suggestion
    on Apr 30, 2021
  7. added
    api-ready-for-review
    blocking
    and removed
    api-suggestion
    on May 13, 2021
  8. bartonjs commented on May 21, 2021

    @bartonjs
    Member

    Video

    • Because the JsonContent type is currently sealed with a non-public constructor there's more flexibility and we can add the JsonContent<T> : JsonContent relationship.
    • The JsonContent.Create that takes a TValue parameter should be declared generic (typo).
    namespace System.Net.Http.Json
    {
        public sealed partial class JsonContent<TValue> : JsonContent
        {
            internal JsonContent() { }
            public TValue? Value { get { throw null; } }
        }
        partial class JsonContent
        {
            public static JsonContent<object?> Create(object? inputValue, Type inputType, JsonSerializerContext context, MediaTypeHeaderValue? mediaType = null) { throw null; }
            public static JsonContent<TValue> Create<TValue>(TValue? inputValue, JsonTypeInfo<TValue> jsonTypeInfo, MediaTypeHeaderValue? mediaType = null) { throw null; }
        }
    }
    namespace System.Net.Http.Json
    {
    -    public sealed partial class JsonContent
    +    public abstract partial class JsonContent
         {
            internal JsonContent();
         }
    +   internal sealed partial class ReflectionBasedJsonContent  : JsonContent { ... }
    }
  9. added
    api-approved
    and removed
    api-ready-for-review
    on May 21, 2021
  10. removed
    blocking
    on May 21, 2021
  11. 30 remaining items

  12. removed
    Priority:1
    on Jun 15, 2023
  13. bartonjs commented on Jul 27, 2023

    @bartonjs
    Member

    Video

    Looks good as proposed (modulo typos)

    namespace System.Net.Http.Json
    {
        public partial class JsonContent
        {
            public static JsonContent Create<TValue>(TValue? inputValue, JsonTypeInfo<TValue> jsonTypeInfo, MediaTypeHeaderValue? mediaType = null);
            public static JsonContent Create(object? inputValue, JsonTypeInfo jsonTypeInfo, MediaTypeHeaderValue? mediaType = null);
        }
    }
  14. added
    api-approved
    and removed
    api-ready-for-review
    on Jul 27, 2023
  15. brantburnett commented on Jul 27, 2023

    @brantburnett
    Contributor

    Great to see this API approved! I'd still love to take this on if that helps, just let me know. I don't want to cross streams if someone is planning to take this internally.

  16. modified the milestones: Future, 9.0.0 on Jul 27, 2023
  17. eiriktsarpalis commented on Jul 27, 2023

    @eiriktsarpalis
    Member

    Feel free to pick it up @brantburnett

  18. ghost added
    in-pr
    on Jul 28, 2023
  19. modified the milestones: 9.0.0, 8.0.0 on Jul 31, 2023
  20. ghost removed
    in-pr
    on Jul 31, 2023
  21. ghost locked as resolved and limited conversation to collaborators on Aug 30, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Cost:Sapi-approvedarea-System.Text.Jsonsource-generator

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions