-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Closed
Labels
Description
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.
- ID: 5de37d79-751f-e372-e866-efde28f4908c
- Version Independent ID: 678c4f23-764a-7ccd-0d6d-159a30957477
- Content: How to write custom converters for JSON serialization - .NET
- Content Source: docs/standard/serialization/system-text-json-converters-how-to.md
- Product: dotnet-fundamentals
- GitHub Login: @tdykstra
- Microsoft Alias: tdykstra