@@ -94,9 +94,15 @@ void AddUserMappings(bool jsonb, Type[] clrTypes)
9494 if ( ! jsonType . IsValueType && jsonTypeInfo . PolymorphismOptions is not null )
9595 {
9696 foreach ( var derived in jsonTypeInfo . PolymorphismOptions . DerivedTypes )
97+ {
98+ // For jsonb we can't properly support polymorphic serialization unless the SerializerOptions.AllowOutOfOrderMetadataProperties is `true`.
99+ // If `jsonb` AND `AllowOutOfOrderMetadataProperties` is `false`, use `derived.DerivedType` as the base type for the converter,
100+ // this causes STJ to stop serializing the "$type" field; essentially disabling the feature.
101+ var baseType = jsonb && ! serializerOptions . AllowOutOfOrderMetadataProperties ? derived . DerivedType : jsonType ;
97102 dynamicMappings . AddMapping ( derived . DerivedType , dataTypeName ,
98103 factory : ( options , mapping , _ ) => mapping . CreateInfo ( options ,
99- CreateSystemTextJsonConverter ( mapping . Type , jsonb , options . TextEncoding , serializerOptions , jsonType ) ) ) ;
104+ CreateSystemTextJsonConverter ( mapping . Type , jsonb , options . TextEncoding , serializerOptions , baseType ) ) ) ;
105+ }
100106 }
101107 }
102108 mappings . AddRange ( dynamicMappings . ToTypeInfoMappingCollection ( ) ) ;
@@ -116,9 +122,10 @@ void AddUserMappings(bool jsonb, Type[] clrTypes)
116122 {
117123 var jsonb = dataTypeName == DataTypeNames . Jsonb ;
118124
119- // For jsonb we can't properly support polymorphic serialization unless we do quite some additional work
120- // so we default to mapping.Type instead (exact types will never serialize their "$type" fields, essentially disabling the feature).
121- var baseType = jsonb ? mapping . Type : typeof ( object ) ;
125+ // For jsonb we can't properly support polymorphic serialization unless the SerializerOptions.AllowOutOfOrderMetadataProperties is `true`.
126+ // If `jsonb` AND `AllowOutOfOrderMetadataProperties` is `false`, use `mapping.Type` as the base type for the converter,
127+ // this causes STJ to stop serializing the "$type" field; essentially disabling the feature.
128+ var baseType = jsonb && ! SerializerOptions . AllowOutOfOrderMetadataProperties ? mapping . Type : typeof ( object ) ;
122129
123130 return mapping . CreateInfo ( options ,
124131 CreateSystemTextJsonConverter ( mapping . Type , jsonb , options . TextEncoding , SerializerOptions , baseType ) ) ;
0 commit comments