Skip to content

ReferenceHandler.Preserve does not work well with JsonConverters #21777

@YeskaNova

Description

@YeskaNova

When I use a simple JsonConverter, with Reference handler equal to Preserve to serialize cyclic objects, the $id property added to each object is not unique, in this example "$id":1 exists two times :

System.Text.Json : 5.0.0

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

namespace ConsoleApp2
{
    public class ActionResultDto<T>
    {
        public T Result { get; set; }
    }
    public class Data
    {
    }
    class Program
    {
        static void Main(string[] args)
        {
            var data = new ActionResultDto<object>
            {
                Result = new Data() 
            };
            var options = new JsonSerializerOptions()
            {
                ReferenceHandler = ReferenceHandler.Preserve
            };
            options.Converters.Add(new EmptyJsonConverter());
            var str = JsonSerializer.Serialize(data, options);
            Debug.Assert(str.Split("\"$id\":\"1\"").Length == 2); // we must have only one occurence of "$id":"1"
        }
    }
    internal class EmptyJsonConverter
       : JsonConverter<object>
    {
        public override object Read(ref Utf8JsonReader reader,Type typeToConvert,JsonSerializerOptions options)
        {
            throw new InvalidOperationException("Should not get here.");
        }

        public override void Write(Utf8JsonWriter writer,object objectToWrite,JsonSerializerOptions options)
        {
            JsonSerializer.Serialize(writer, objectToWrite, options);
        }
    }
}

// Output =>    {"$id":"1","Result":{"$id":"1"}}

Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions