Skip to content

JsonSerializer.Serialize throws StackOverflowException serializing dictionary with string key and object-converter that handles string #118381

@vsfeedback

Description

@vsfeedback

This issue has been moved from a ticket on Developer Community.


[severity:It's more difficult to complete my work]
Having a custom "generic" serializer that handles multiple types (including string) and then serializing a dictionary with string key makes the Serialize call to get stuck in a forever loop (with stack overflow exception as result). Perhaps a bit odd use case but I stumbled on it after converting from Newtonsoft to .NET so I just let you know in any case. My real use case is a bit more complicated as usual but this is what I could boil it down to:

using System.Text.Json;
using System.Text.Json.Serialization;

namespace JsonSerializationTest
{
    // example minimal "generic" converter
    public class GenericJsonConverter : JsonConverter<object> // using string here works but that is not an option for my real usecase
    {
        public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(string);
        public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => reader.GetString();
        public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToString());
    }

    public class Tests
    {
        [Test]
        public void DoesNotWork()
        {
            var options = new JsonSerializerOptions();
            options.Converters.Add(new GenericJsonConverter());
            var value = new Dictionary<string, int> { { "key", 123 } };
            Assert.That(() => JsonSerializer.Serialize(value, options), Throws.InstanceOf<StackOverflowException>());
        }

        [Test]
        public void Works()
        {
            var options = new JsonSerializerOptions();
            var value = new Dictionary<string, int> { { "key", 123 } };
            Assert.DoesNotThrow(() => JsonSerializer.Serialize(value, options));
        }
    }
}

Original Comments

Feedback Bot on 14/07/2025, 09:07 AM:

We have directed your feedback to the appropriate engineering team for further evaluation. The team will review the feedback and notify you about the next steps.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions