Skip to content

Commit afc562e

Browse files
committed
Fix voption and Skippable as union fields
1 parent f7493e9 commit afc562e

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

src/FSharp.SystemTextJson/Union.fs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ namespace System.Text.Json.Serialization
22

33
open System
44
open System.Collections.Generic
5+
open System.Runtime.Serialization
56
open System.Text.Json
6-
open FSharp.Reflection
77
open System.Text.Json.Serialization.Helpers
8-
open System.Buffers
8+
open FSharp.Reflection
99

1010
type private Field =
1111
{
@@ -19,6 +19,7 @@ type private Field =
1919
type private Case =
2020
{
2121
Fields: Field[]
22+
DefaultFields: obj[]
2223
FieldsByName: Dictionary<string, struct (int * Field)> voption
2324
Ctor: obj[] -> obj
2425
Dector: obj -> obj[]
@@ -93,8 +94,18 @@ type JsonUnionConverter<'T>
9394
ValueOption.isNone unwrappedRecordField
9495
&& fields.Length = 1
9596
&& fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapSingleFieldCases
97+
let defaultFields =
98+
let arr = Array.zeroCreate fields.Length
99+
fields
100+
|> Array.iteri (fun i field ->
101+
if isSkippableType field.Type || isValueOptionType field.Type then
102+
let case = FSharpType.GetUnionCases(field.Type).[0]
103+
arr.[i] <- FSharpValue.MakeUnion(case, [||])
104+
)
105+
arr
96106
{
97107
Fields = fields
108+
DefaultFields = defaultFields
98109
FieldsByName = fieldsByName
99110
Ctor = FSharpValue.PreComputeUnionConstructor(uci, true)
100111
Dector = FSharpValue.PreComputeUnionReader(uci, true)
@@ -250,7 +261,7 @@ type JsonUnionConverter<'T>
250261

251262
let readFieldsAsRestOfArray (reader: byref<Utf8JsonReader>) (case: Case) (options: JsonSerializerOptions) =
252263
let fieldCount = case.Fields.Length
253-
let fields = Array.zeroCreate fieldCount
264+
let fields = Array.copy case.DefaultFields
254265
for i in 0..fieldCount-1 do
255266
fields.[i] <- readField &reader case case.Fields.[i] options
256267
readExpecting JsonTokenType.EndArray "end of array" &reader ty
@@ -262,7 +273,7 @@ type JsonUnionConverter<'T>
262273

263274
let coreReadFieldsAsRestOfObject (reader: byref<Utf8JsonReader>) (case: Case) (skipFirstRead: bool) (options: JsonSerializerOptions) =
264275
let fieldCount = case.Fields.Length
265-
let fields = Array.zeroCreate fieldCount
276+
let fields = Array.copy case.DefaultFields
266277
let mutable cont = true
267278
let mutable fieldsFound = 0
268279
let mutable skipRead = skipFirstRead

0 commit comments

Comments
 (0)