Diff
checker
텍스트
텍스트
이미지
문서
Excel
폴더
Legal
Enterprise
데스크톱
요금제
로그인
데스크톱 앱 다운로드
텍스트 비교
두 텍스트 파일의 차이점을 찾아보세요
도구
기록
표시
레이아웃
나란히 보기
합쳐 보기
실시간 편집
공백 변경 숨기기
변경 없는 행 숨기기
줄바꿈 비활성화
비교 단위
스마트
구문
없음
모양 변경
처리
제외
텍스트 변환
첫 변경으로
수정
Diffchecker Desktop
가장 안전하게 Diffchecker를 사용하는 방법. 데스크톱 앱을 사용하면 비교 데이터가 외부로 전송되지 않습니다!
데스크톱 앱 받기
object-polymorphism-STJ
생성일
11개월 전
비교 결과 만료 없음
초기화
내보내기
공유
설명
1 삭제
행
총
삭제
글자
총
삭제
이 기능을 계속 사용하려면 업그레이드해 주세요
Diff
checker
Pro
요금제 보기
45 행
복사
61 추가
행
총
추가
글자
총
추가
이 기능을 계속 사용하려면 업그레이드해 주세요
Diff
checker
Pro
요금제 보기
101 행
복사
#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;
복사
복사됨
복사
복사됨
var jsonSettings = new JsonSerializerOptions
{
var jsonSettings = new JsonSerializerOptions
{
IncludeFields = true,
IncludeFields = true,
TypeInfoResolver = new DefaultJsonTypeInfoResolver().WithAddedModifier(AddAbcHierarchy<A>),
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 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))
{
{
복사
복사됨
복사
복사됨
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; }
복사
복사됨
복사
복사됨
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);
}
}
저장된 비교 결과
원본
파일 열기
#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; }
수정본
파일 열기
#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); } }
비교하기