Diff
checker
Text
Text
Images
Documents
Excel
Folders
Legal
Enterprise
Desktop
Pricing
Sign in
Download Diffchecker Desktop
Compare text
Find the difference between two text files
Tools
History
Display
Layout
Split
Unified
Real-time editor
Hide whitespace changes
Hide unchanged lines
Disable line wrap
Diff precision
Smart
Syntax
None
Change appearance
Process
Ignore
Transform text
Go to first change
Edit input
Diffchecker Desktop
The most secure way to run Diffchecker. Get the Diffchecker Desktop app: your diffs never leave your computer!
Get Desktop
object-polymorphism-STJ
Created
11 months ago
Diff never expires
Clear
Export
Share
Explain
1 removal
Lines
Total
Removed
Characters
Total
Removed
To continue using this feature, upgrade to
Diff
checker
Pro
View Pricing
45 lines
Copy
61 additions
Lines
Total
Added
Characters
Total
Added
To continue using this feature, upgrade to
Diff
checker
Pro
View Pricing
101 lines
Copy
#pragma warning disable IL2026
#pragma warning disable IL2026
#pragma warning disable IL3050
#pragma warning disable IL3050
using System.Text.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Text.Json.Serialization.Metadata;
Copy
Copied
Copy
Copied
var jsonSettings = new JsonSerializerOptions
{
var jsonSettings = new JsonSerializerOptions
{
IncludeFields = true,
IncludeFields = true,
TypeInfoResolver = new DefaultJsonTypeInfoResolver().WithAddedModifier(AddAbcHierarchy<A>),
TypeInfoResolver = new DefaultJsonTypeInfoResolver().WithAddedModifier(AddAbcHierarchy<A>),
};
};
Copy
Copied
Copy
Copied
jsonSettings.Converters.Add(new DiscriminatedObjectConverter(
new Dictionary<string, Type> { ["A"] = typeof(A), ["B"] = typeof(B), ["C"] = typeof(C) }
));
var c = new C { Id = 1, Price = 9.99 };
var c = new C { Id = 1, Price = 9.99 };
var json1 = JsonSerializer.Serialize<A>(c, jsonSettings);
var json1 = JsonSerializer.Serialize<A>(c, jsonSettings);
Console.WriteLine(json1);
Console.WriteLine(json1);
var obj1 = JsonSerializer.Deserialize<A>(json1, jsonSettings);
var obj1 = JsonSerializer.Deserialize<A>(json1, jsonSettings);
Console.WriteLine(obj1?.GetType().Name);
Console.WriteLine(obj1?.GetType().Name);
var json2 = JsonSerializer.Serialize<object>(c, jsonSettings);
var json2 = JsonSerializer.Serialize<object>(c, jsonSettings);
Console.WriteLine(json2);
Console.WriteLine(json2);
var obj2 = JsonSerializer.Deserialize<object>(json2, jsonSettings);
var obj2 = JsonSerializer.Deserialize<object>(json2, jsonSettings);
Console.WriteLine(obj2?.GetType().Name);
Console.WriteLine(obj2?.GetType().Name);
return;
return;
static void AddAbcHierarchy<TBase>(JsonTypeInfo jsonTypeInfo)
static void AddAbcHierarchy<TBase>(JsonTypeInfo jsonTypeInfo)
{
{
if (jsonTypeInfo.Type == typeof(TBase))
if (jsonTypeInfo.Type == typeof(TBase))
{
{
Copy
Copied
Copy
Copied
var polymorphismOptions = new JsonPolymorphismOptions
{
var polymorphismOptions = new JsonPolymorphismOptions
{
TypeDiscriminatorPropertyName = "$type",
TypeDiscriminatorPropertyName = "$type",
IgnoreUnrecognizedTypeDiscriminators = false,
IgnoreUnrecognizedTypeDiscriminators = false,
UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType,
UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType,
};
};
var deriveTypes = polymorphismOptions.DerivedTypes;
var deriveTypes = polymorphismOptions.DerivedTypes;
deriveTypes.Add(new JsonDerivedType(typeof(A), "A"));
deriveTypes.Add(new JsonDerivedType(typeof(A), "A"));
deriveTypes.Add(new JsonDerivedType(typeof(B), "B"));
deriveTypes.Add(new JsonDerivedType(typeof(B), "B"));
deriveTypes.Add(new JsonDerivedType(typeof(C), "C"));
deriveTypes.Add(new JsonDerivedType(typeof(C), "C"));
jsonTypeInfo.PolymorphismOptions = polymorphismOptions;
jsonTypeInfo.PolymorphismOptions = polymorphismOptions;
}
}
}
}
class A { public int Id; }
class A { public int Id; }
Copy
Copied
Copy
Copied
class B
: A { public string? Description; }
class B
: A { public string? Description; }
class C
: A { public double Price; }
class C
: A { public double Price; }
file sealed class DiscriminatedObjectConverter : JsonConverter<object>
{
private readonly IReadOnlyDictionary<string, Type> _map;
private readonly string _disc;
public DiscriminatedObjectConverter(
IReadOnlyDictionary<string, Type> map,
string discriminatorPropertyName = "$type")
{
_map = map;
_disc = discriminatorPropertyName;
}
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(object);
public override object? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using var doc = JsonDocument.ParseValue(ref reader);
var root = doc.RootElement;
if (root.ValueKind == JsonValueKind.Object &&
root.TryGetProperty(_disc, out var discProp) &&
discProp.ValueKind == JsonValueKind.String)
{
var id = discProp.GetString();
if (id != null && _map.TryGetValue(id, out var toType))
{
return root.Deserialize(toType, options)!;
}
}
// Fall back to default behavior: keep it as JsonElement
return root.Clone();
}
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
// If it's part of the A hierarchy, serialize *as A* to trigger polymorphism and emit $type.
if (value is A a)
{
JsonSerializer.Serialize<A>(writer, a, options);
return;
}
// Otherwise, fall back to the runtime type.
JsonSerializer.Serialize(writer, value, value?.GetType() ?? typeof(object), options);
}
}
Saved diffs
Original text
Open file
#pragma warning disable IL2026 #pragma warning disable IL3050 using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; var jsonSettings = new JsonSerializerOptions { IncludeFields = true, TypeInfoResolver = new DefaultJsonTypeInfoResolver().WithAddedModifier(AddAbcHierarchy<A>), }; var c = new C { Id = 1, Price = 9.99 }; var json1 = JsonSerializer.Serialize<A>(c, jsonSettings); Console.WriteLine(json1); var obj1 = JsonSerializer.Deserialize<A>(json1, jsonSettings); Console.WriteLine(obj1?.GetType().Name); var json2 = JsonSerializer.Serialize<object>(c, jsonSettings); Console.WriteLine(json2); var obj2 = JsonSerializer.Deserialize<object>(json2, jsonSettings); Console.WriteLine(obj2?.GetType().Name); return; static void AddAbcHierarchy<TBase>(JsonTypeInfo jsonTypeInfo) { if (jsonTypeInfo.Type == typeof(TBase)) { var polymorphismOptions = new JsonPolymorphismOptions { TypeDiscriminatorPropertyName = "$type", IgnoreUnrecognizedTypeDiscriminators = false, UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType, }; var deriveTypes = polymorphismOptions.DerivedTypes; deriveTypes.Add(new JsonDerivedType(typeof(A), "A")); deriveTypes.Add(new JsonDerivedType(typeof(B), "B")); deriveTypes.Add(new JsonDerivedType(typeof(C), "C")); jsonTypeInfo.PolymorphismOptions = polymorphismOptions; } } class A { public int Id; } class B: A { public string? Description; } class C: A { public double Price; }
Changed text
Open file
#pragma warning disable IL2026 #pragma warning disable IL3050 using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; var jsonSettings = new JsonSerializerOptions { IncludeFields = true, TypeInfoResolver = new DefaultJsonTypeInfoResolver().WithAddedModifier(AddAbcHierarchy<A>), }; jsonSettings.Converters.Add(new DiscriminatedObjectConverter( new Dictionary<string, Type> { ["A"] = typeof(A), ["B"] = typeof(B), ["C"] = typeof(C) } )); var c = new C { Id = 1, Price = 9.99 }; var json1 = JsonSerializer.Serialize<A>(c, jsonSettings); Console.WriteLine(json1); var obj1 = JsonSerializer.Deserialize<A>(json1, jsonSettings); Console.WriteLine(obj1?.GetType().Name); var json2 = JsonSerializer.Serialize<object>(c, jsonSettings); Console.WriteLine(json2); var obj2 = JsonSerializer.Deserialize<object>(json2, jsonSettings); Console.WriteLine(obj2?.GetType().Name); return; static void AddAbcHierarchy<TBase>(JsonTypeInfo jsonTypeInfo) { if (jsonTypeInfo.Type == typeof(TBase)) { var polymorphismOptions = new JsonPolymorphismOptions { TypeDiscriminatorPropertyName = "$type", IgnoreUnrecognizedTypeDiscriminators = false, UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType, }; var deriveTypes = polymorphismOptions.DerivedTypes; deriveTypes.Add(new JsonDerivedType(typeof(A), "A")); deriveTypes.Add(new JsonDerivedType(typeof(B), "B")); deriveTypes.Add(new JsonDerivedType(typeof(C), "C")); jsonTypeInfo.PolymorphismOptions = polymorphismOptions; } } class A { public int Id; } class B : A { public string? Description; } class C : A { public double Price; } file sealed class DiscriminatedObjectConverter : JsonConverter<object> { private readonly IReadOnlyDictionary<string, Type> _map; private readonly string _disc; public DiscriminatedObjectConverter( IReadOnlyDictionary<string, Type> map, string discriminatorPropertyName = "$type") { _map = map; _disc = discriminatorPropertyName; } public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(object); public override object? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using var doc = JsonDocument.ParseValue(ref reader); var root = doc.RootElement; if (root.ValueKind == JsonValueKind.Object && root.TryGetProperty(_disc, out var discProp) && discProp.ValueKind == JsonValueKind.String) { var id = discProp.GetString(); if (id != null && _map.TryGetValue(id, out var toType)) { return root.Deserialize(toType, options)!; } } // Fall back to default behavior: keep it as JsonElement return root.Clone(); } public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) { // If it's part of the A hierarchy, serialize *as A* to trigger polymorphism and emit $type. if (value is A a) { JsonSerializer.Serialize<A>(writer, a, options); return; } // Otherwise, fall back to the runtime type. JsonSerializer.Serialize(writer, value, value?.GetType() ?? typeof(object), options); } }
Find difference