Skip to content

Commit d090ada

Browse files
Account for CompilationMappingAttribute supporting multiple declarations. (#115076)
Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>
1 parent 753e467 commit d090ada

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/FSharpCoreReflectionProxy.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -204,15 +204,18 @@ public Func<IEnumerable<Tuple<TKey, TValue>>, TFSharpMap> CreateFSharpMapConstru
204204
}
205205

206206
private Attribute? GetFSharpCompilationMappingAttribute(Type type)
207-
=> type.GetCustomAttribute(_compilationMappingAttributeType, inherit: true);
207+
{
208+
object[] attributes = type.GetCustomAttributes(_compilationMappingAttributeType, inherit: false);
209+
return attributes.Length == 0 ? null : (Attribute)attributes[0];
210+
}
208211

209212
private SourceConstructFlags GetSourceConstructFlags(Attribute compilationMappingAttribute)
210213
=> _sourceConstructFlagsGetter is null ? SourceConstructFlags.None : (SourceConstructFlags)_sourceConstructFlagsGetter.Invoke(compilationMappingAttribute, null)!;
211214

212215
// If the provided type is generated by the F# compiler, returns the runtime FSharp.Core assembly.
213216
private static Assembly? GetFSharpCoreAssembly(Type type)
214217
{
215-
foreach (Attribute attr in type.GetCustomAttributes(inherit: true))
218+
foreach (Attribute attr in type.GetCustomAttributes(inherit: false))
216219
{
217220
Type attributeType = attr.GetType();
218221
if (attributeType.FullName == CompilationMappingAttributeTypeName)

src/libraries/System.Text.Json/tests/System.Text.Json.FSharp.Tests/RecordTests.fs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,3 +76,22 @@ let ``Recursive struct records are supported``() =
7676
Assert.Equal("""{"Next":[{"Next":[null]}]}""", json)
7777
let deserializedValue = JsonSerializer.Deserialize<RecursiveStructRecord>(json)
7878
Assert.Equal(value, deserializedValue)
79+
80+
81+
[<JsonDerivedType(typeof<DerivedClass>, "derived")>]
82+
type BaseClass(x : int) =
83+
member _.X = x
84+
85+
and DerivedClass(x : int, y : bool) =
86+
inherit BaseClass(x)
87+
member _.Y = y
88+
89+
[<Fact>]
90+
let ``Support F# class hierarchies`` () =
91+
let value = DerivedClass(42, true) :> BaseClass
92+
let json = JsonSerializer.Serialize(value)
93+
Assert.Equal("""{"$type":"derived","Y":true,"X":42}""", json)
94+
let deserializedValue = JsonSerializer.Deserialize<BaseClass>(json)
95+
let derived = Assert.IsType<DerivedClass>(deserializedValue)
96+
Assert.Equal(42, deserializedValue.X)
97+
Assert.Equal(true, derived.Y)

0 commit comments

Comments
 (0)