Skip to content

JsonSerializerOptions.GetTypeInfo throws when TypeInfoResolver is null #80529

Closed
@brunolins16

Description

@brunolins16

Description

JsonSerializerOptions.TypeInfoResolver is documented as:

A <see langword="null"/> setting is equivalent to using the reflection-based <see cref="[DefaultJsonTypeInfoResolver](https://source.dot.net/System.Text.Json/P/29c640504d3d4bbe.html#29c640504d3d4bbe)" />.
        /// The property will be populated automatically once used with one of the <see cref="[JsonSerializer](https://source.dot.net/System.Text.Json/P/2ca342a99419a245.html#2ca342a99419a245)"/> methods.

This behavior works correctly, however if instead try to obtain the JsonTypeInfo from the JsonSerializerOptions before calling the serializer it fails.

cc @davidfowl @eiriktsarpalis

Reproduction Steps

using System.Text.Json;

var options = new JsonSerializerOptions();
var typeinfo = options.GetTypeInfo(typeof(string));

Expected behavior

When JsonSerializerOptions.TypeInfoResolver is null and a call to JsonSerializerOptions.GetTypeInfo happens it should behave similarly to a call to the JsonSerializer methods.

Probably in AOT-mode DefaultJsonTypeInfoResolver should not need to be set and throws at runtime might be ok.

Actual behavior

System.NotSupportedException
  HResult=0x80131515
  Message=Metadata for type 'System.String' was not provided by TypeInfoResolver of type '<null>'. If using source generation, ensure that all root types passed to the serializer have been indicated with 'JsonSerializableAttribute', along with any types that might be serialized polymorphically.
  Source=System.Text.Json
  StackTrace:
   at System.Text.Json.ThrowHelper.ThrowNotSupportedException_NoMetadataForType(Type type, IJsonTypeInfoResolver resolver) in /_/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.Serialization.cs:line 709
   at System.Text.Json.JsonSerializerOptions.GetTypeInfoInternal(Type type, Boolean ensureConfigured, Boolean resolveIfMutable) in /_/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs:line 75
   at Program.<Main>$(String[] args) in C:\Users\brolivei\source\repos\WebApplication24\Program.cs:line 5

Regression?

No response

Known Workarounds

Manually instantiate the JsonSerializerOptions with the DefaultJsonTypeInfoResolver

eg.:

var options = new JsonSerializerOptions() { TypeInfoResolver = new DefaultJsonTypeInfoResolver() } ;

Configuration

.NET 7

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.Jsonbreaking-changeIssue or PR that represents a breaking API or functional change over a prerelease.partner-impactThis issue impacts a partner who needs to be kept updated

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions