Deserialize interfaces using System.Text.Json.JsonSerializer #87545
Unanswered
douglasg14b
asked this question in
General
Replies: 1 comment 4 replies
-
Deserialization via string json = JsonSerializer.Serialize(new Node { Value = "value" }); // { "$type" : "node", "Value" : "value" }
JsonSerializer.Deserialize<INode>(json) is Node; // true
[JsonDerivedType(typeof(Node), "node")]
interface INode
{
string Value { get; set; }
} Please see the relevant article for more details. If polymorphism is not what you were specifically looking for, and you just want the serializer to always fill in var options = new JsonSerializerOptions
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver
{
Modifiers =
{
static typeInfo =>
{
if (typeInfo.Type == typeof(INode))
{
typeInfo.CreateObject = () => new Node();
}
}
}
}
};
JsonSerializer.Deserialize<INode>("{}", options) is Node; // true Hope this helps. |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
#30956 seems to have been the original request for this, however it's closed as completed, but there is still no support for JSON Serialization of interfaces as of .Net 7...?
Following through this chain of issues #30956 -> #30083 -> #63747 -> #71346
It's suggested in the implementation noted in #63747 that the following would allow for interface de-serialization:
Hhowever doing something similar to this results in a pretty clear exception:
All threads I could find related to this feature are closed as completed. So here I am!
Is this a feature already tracked?
Beta Was this translation helpful? Give feedback.
All reactions