@@ -2,10 +2,10 @@ namespace System.Text.Json.Serialization
2
2
3
3
open System
4
4
open System.Collections .Generic
5
+ open System.Runtime .Serialization
5
6
open System.Text .Json
6
- open FSharp.Reflection
7
7
open System.Text .Json .Serialization .Helpers
8
- open System. Buffers
8
+ open FSharp. Reflection
9
9
10
10
type private Field =
11
11
{
@@ -19,6 +19,7 @@ type private Field =
19
19
type private Case =
20
20
{
21
21
Fields: Field []
22
+ DefaultFields: obj []
22
23
FieldsByName: Dictionary < string , struct ( int * Field )> voption
23
24
Ctor: obj [] -> obj
24
25
Dector: obj -> obj []
@@ -93,8 +94,18 @@ type JsonUnionConverter<'T>
93
94
ValueOption.isNone unwrappedRecordField
94
95
&& fields.Length = 1
95
96
&& 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
96
106
{
97
107
Fields = fields
108
+ DefaultFields = defaultFields
98
109
FieldsByName = fieldsByName
99
110
Ctor = FSharpValue.PreComputeUnionConstructor( uci, true )
100
111
Dector = FSharpValue.PreComputeUnionReader( uci, true )
@@ -250,7 +261,7 @@ type JsonUnionConverter<'T>
250
261
251
262
let readFieldsAsRestOfArray ( reader : byref < Utf8JsonReader >) ( case : Case ) ( options : JsonSerializerOptions ) =
252
263
let fieldCount = case.Fields.Length
253
- let fields = Array.zeroCreate fieldCount
264
+ let fields = Array.copy case.DefaultFields
254
265
for i in 0 .. fieldCount-1 do
255
266
fields.[ i] <- readField & reader case case.Fields.[ i] options
256
267
readExpecting JsonTokenType.EndArray " end of array" & reader ty
@@ -262,7 +273,7 @@ type JsonUnionConverter<'T>
262
273
263
274
let coreReadFieldsAsRestOfObject ( reader : byref < Utf8JsonReader >) ( case : Case ) ( skipFirstRead : bool ) ( options : JsonSerializerOptions ) =
264
275
let fieldCount = case.Fields.Length
265
- let fields = Array.zeroCreate fieldCount
276
+ let fields = Array.copy case.DefaultFields
266
277
let mutable cont = true
267
278
let mutable fieldsFound = 0
268
279
let mutable skipRead = skipFirstRead
0 commit comments