Repository navigation
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedarea-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additions
Milestone
Description
EDIT See #72604 (comment) for an API proposal.
Description
Attempting to deserialize a polymorphic structure with System.Text.Json that doesn't feature $type at start of the object results in an exception.
For my scenario, this currently prevents me from using the built-in polymorphism support with jsonb columns in Postgres, as object properties have no guaranteed order.
Developer comment on this issue: #63747 (comment)
Reproduction Steps
var databaseState = @"{
""BaseDictionary"": {
""6ed6e524-2ca4-4fea-8e21-7245ccb61863"": {
""Id"": ""6ed6e524-2ca4-4fea-8e21-7245ccb61863"",
""Name"": ""Something"",
""$type"": ""Derived"",
""OtherGuid"": ""d471c77d-5412-4e7a-a98d-8304e87792ed""
}
}
}";
JsonSerializer.Deserialize<WrapperType>(databaseState);
public record WrapperType(Dictionary<Guid, WrapperType.Base> BaseDictionary)
{
[JsonDerivedType(typeof(Derived), nameof(Derived))]
[JsonDerivedType(typeof(AlsoDerived), nameof(AlsoDerived))]
public abstract record Base(Guid Id, string Name);
public record Derived(Guid Id, string Name, Guid OtherGuid): Base(Id, Name);
public record AlsoDerived(Guid Id, string Name) : Base(Id, Name);
}Expected behavior
Deserialization should work.
Actual behavior
System.NotSupportedException: 'Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported.
Regression?
Limitation of initial implementation
Known Workarounds
I currently use PolyJson as an alternative, as the implementation reads ahead to find the discriminator.
Configuration
Impacts any version of STJ 7.0
Other information
No response
Reacted by Amadeusz Sadowski, nenoNaninu, Ryan Gaudion, Ilya Chernomordik, Kelvin, Jake Yallop, Troy Steinbauer, tkvalvik, Sebastian Stehle, xiety and 67 more
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedarea-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additions
Activity
eiriktsarpalis commentedon Jul 21, 2022
Per #63747 (comment) this is a known limitation of the metadata reader. In the future we might consider adding read-ahead support specifically for type discriminators (I don't believe reference preservation to have such requirements), but this would be at the expense of potentially buffering excessive data in the case of async serialization.
ilya-scale commentedon Oct 3, 2022
Is there any known workaround for this? I want to deserialize an object that does not come from
System.Text.Jsonbut has a discriminator that can be used that is of course not guaranteed to be first. The only thing I managed so far is to just deserialized first that one field and then specify type explicitly (i.e. not using the new polymorphic deserialization at all).Maybe there is something else that can be done, like e.g. explicit reordering or something like that?
eiriktsarpalis commentedon Oct 3, 2022
No workaround that doesn't involve writing a custom converter, unfortunately. In the future we might consider exposing a flag that reads ahead for type discriminators, but obviously that would come at the expense of performance so it would be turned off by default.
ilya-scale commentedon Oct 3, 2022
Thanks for the answer! I assume the "future" will not be in .Net 7, so not coming anytime soon, right?
eiriktsarpalis commentedon Oct 3, 2022
Correct, .NET 7 is currently in RC so feature development has been concluded.
JobaDiniz commentedon Oct 15, 2022
Why can't I use my own property for the type discriminator?
My object has a
string Typeproperty already. According to this documentationit says:
I would like to tell
System.Text.Jsonthat there is a property (the first one) namedType, just use it.eiriktsarpalis commentedon Oct 17, 2022
The value of a string property can be arbitrary and might not necessarily reflect the runtime type of the object you are trying to serialize. In your example I would simply annotate the
Typeproperty withJsonIgnoreAttribute.kOchirasu commentedon Nov 8, 2022
I have this issue as well. When serializing JSON to MySQL using ef core, it seems that the ordering is not preserved so the data cannot be deserialized anymore.
There is a bit of a hack to work around this since MySQL seems to do deterministic ordering:
You might be able to get away with " " (space) as well, but basically a very low value ascii character that's valid will cause it to be sorted first. Definitely would not recommend doing this in production, but I am using this for myself.
SebastianStehle commentedon Nov 9, 2022
With .NET 7 I have a solution that should be at least fast.
I have a custom converter (in this case it is abstract because I have different ways to resolve type and discriminator) to handle writing and reading:
The problem was always the writing part, because you have to buffer the resulting object:
So you effectively write the object, then you deserialize it and then you serialize it again. So my idea with .NET 7 was to add a custom property to the contract with a custom resolver. You cannot use modifiers, because you need the type info of the base class.
I don't like that you need the type resolver and the converter right now, but I do not see another option.
53 remaining items
eiriktsarpalis commentedon Jan 22, 2024
Yes, the metadata reader checks for a number of properties that need to be validated (invalid combinations, duplicates, etc.) so it can't just stop on the first occurrence of
$type.[-]Polymorphic Deserialization throws if $type metadata isn't present at the start of the object[/-][+]JsonSerializer: Allow out-of-order reading of metadata properties.[/+]eiriktsarpalis commentedon Jan 24, 2024
Candidate implementation: #97474
bartonjs commentedon Jan 30, 2024
Video
Looks good as proposed. The default may need to change from false to true in the future; but we'll let that be based on data/feedback.
eiriktsarpalis commentedon Feb 2, 2024
The new flag should become available with .NET 9 Preview 2.
tyler-boyd commentedon Feb 7, 2024
I know there were a few workarounds posted already, but none of them supported my use case. I don't want to use source generation, and I need it to support nested polymorphic objects as well as always including the discriminator when serializing subclasses (even if we're not casting them to the base class). So, this is what I came up with (by modifying things I saw in this thread and others), hopefully it helps anyone else who needs this behaviour before .NET 9!
Custom attribute and converter
JsonTypeInfo modifier to always include discriminator when writing JSON