Guard against user-provided JsonConverterFactory.CanConvert implementations returning JsonConverterFactory instances
Failing to do so causes a null ref. See repro (https://dotnetfiddle.net/oC7EpM):
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
public class Program
{
public static void Main()
{
JsonSerializerOptions options = new()
{
Converters = { new MyJsonConverterFactory() }
};
JsonSerializer.Serialize(1, options); // NullReferenceException here.
}
public class MyJsonConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type type) => true;
public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options) => new MyJsonConverterFactory();
}
}
To avoid NullReferenceExceptions, we should check in the following method that the return value is not a JsonConverterFactory instance. We already check for null. With these two checks in place, users will be forced to return JsonConverter<T> instances.
https://github.com/dotnet/runtime/blob/acd80580e768441efb2108bddec7fc3f03b6e747/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverterFactory.cs#L58-L69
Tagging subscribers to this area: @eiriktsarpalis, @layomia See info in area-owners.md if you want to be subscribed.
Issue Details
Failing to do so causes a null ref. See repro (https://dotnetfiddle.net/oC7EpM):
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
public class Program
{
public static void Main()
{
JsonSerializerOptions options = new()
{
Converters = { new MyJsonConverterFactory() }
};
JsonSerializer.Serialize(1, options); // NullReferenceException here.
}
public class MyJsonConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type type) => true;
public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options) => new MyJsonConverterFactory();
}
}
To avoid NullReferenceExceptions, we should check in the following method that the return value is not a JsonConverterFactory instance. We already check for null. With these two checks in place, users will be forced to return JsonConverter<T> instances.
https://github.com/dotnet/runtime/blob/acd80580e768441efb2108bddec7fc3f03b6e747/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverterFactory.cs#L58-L69
| Author: | layomia |
|---|---|
| Assignees: | - |
| Labels: |
|
| Milestone: | 6.0.0 |
Hey, I would like to take the bug.
Thanks @SkiFoD, I've assigned this to you.