Closed armanossiloko closed 9 months ago
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis See info in area-owners.md if you want to be subscribed.
Author: | armanossiloko |
---|---|
Assignees: | - |
Labels: | `area-System.Text.Json` |
Milestone: | - |
See this comment and the comment(s) it refers to: https://github.com/dotnet/runtime/issues/72604#issuecomment-1191524754
Closing as duplicate of #72604
I have noticed some behavior that got me surprised. I have an abstract BaseClass and a DerivedClass.
And now I have two JSON strings: the first JSON has the type discriminator (
$type
) as the very first property within the JSON - the second JSON string does not. When I performJsonSerializer.Deserialize<BaseClass>()
, an exception is thrown on the second JSON string.The exception that is thrown is of type
System.NotSupportedException
with the following message:It also has an inner exception:
At first glance I thought this would be a bug until someone pointed out this particular area in the documentation.
Since on the top level of any JSON string, you can't really have duplicate properties (e.g the property
username
cannot really appear twice on the same level within a JSON), why isSystem.Text.Json
designed in such a way to throw this exception?For anyone interested, I came across this while I was trying to map a property to
jsonb
using EntityFrameworkCore and within Npgsql. I did have to wrap the JsonSerializer methods into a new class which for the sake of example is calledDatabaseJsonConverter
below. Also, during the "serialization" part of an object, the$type
does get written as the first property within the resulting JSON, but for some reason, after it's saved, the order of properties in my PostgreSQL instance is not the same it was in themetadata => DatabaseJsonConverter.Serialize(metadata)
resulting string.Image taken from within the database in Datagrip: