Polymorphic deserialization of object #121549
Replies: 4 comments
-
|
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis |
Beta Was this translation helpful? Give feedback.
-
|
You can use a custom converter; discriminator‑based polymorphic deserialization ("$type" mapped to A/B/C): https://www.diffchecker.com/jQPiCRfJ/ |
Beta Was this translation helpful? Give feedback.
-
|
This is very good and works like a charm on public override void Write(
Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
if (value is A a)
{
JsonSerializer.Serialize<A>(writer, a, options);
return;
}
JsonSerializer.Serialize(writer, value, value?.GetType() ?? typeof(object), options);
}Serializing as Serializing as I was thinking for a moment of creating a clone of options without this converter but this would prevent using this converter for any object below (nested objects) and have terrible performance implications. |
Beta Was this translation helpful? Give feedback.
-
|
Do you have a repro? I tried with (only) this change ( var a = new A { Id = 1 };
// var c = new C { Id = 1, Price = 9.99 };
var json1 = JsonSerializer.Serialize<A>(a, jsonSettings);
Console.WriteLine(json1);
var obj1 = JsonSerializer.Deserialize<A>(json1, jsonSettings);
Console.WriteLine(obj1?.GetType().Name);
var json2 = JsonSerializer.Serialize<object>(a, jsonSettings);
Console.WriteLine(json2);
var obj2 = JsonSerializer.Deserialize<object>(json2, jsonSettings);
Console.WriteLine(obj2?.GetType().Name); |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm in between two third-party libraries, one is defining some hierarchy of classes, let's say, A, B and C, the other one does stuff and has pluggable serialization.
I'm trying to use System.Text.Json as a serializer but...
Third party library is serializing my data as
List<object>and when they go in as A, B, and C they all come out on the other side asJsonElement.I tried to configure polymorphic serialization using JsonSerializationOptions and it works just fine for hierarchies until declared serialized type is
object. Then everything becomesJsonElement.In above example, C get serialized/deserialized as A and after deserialization it is correctly reported as C. When it gets serialized/deserialized as object then it is not longer C it is just
JsonElement:NOTE: I understand why it doesn't work, but the question is different: can I make it work at all? is polymorphic serialization possible if declared type is
object?Beta Was this translation helpful? Give feedback.
All reactions