|
3 | 3 | #nowarn "44" // JsonSerializerOptions.IgnoreNullValues is obsolete for users but still relevant for converters. |
4 | 4 |
|
5 | 5 | open System |
| 6 | +open System.Collections.Generic |
6 | 7 | open System.Reflection |
7 | 8 | open System.Text.Json |
8 | 9 | open System.Text.Json.Serialization |
@@ -111,31 +112,38 @@ let rec tryGetNullValue (fsOptions: JsonFSharpOptionsRecord) (ty: Type) : obj vo |
111 | 112 | let isNullableFieldType (fsOptions: JsonFSharpOptionsRecord) (ty: Type) = |
112 | 113 | tryGetNullValue fsOptions ty |> ValueOption.isSome |
113 | 114 |
|
| 115 | +let private tryGetTypeOrGeneric (ty: Type) (types: IDictionary<Type, _>) = |
| 116 | + let mutable res = Unchecked.defaultof<_> |
| 117 | + if isNull types then |
| 118 | + ValueNone |
| 119 | + elif types.TryGetValue(ty, &res) then |
| 120 | + ValueSome res |
| 121 | + elif ty.IsGenericType && types.TryGetValue(ty.GetGenericTypeDefinition(), &res) then |
| 122 | + ValueSome res |
| 123 | + else |
| 124 | + ValueNone |
| 125 | + |
114 | 126 | let overrideOptions (ty: Type) (defaultOptions: JsonFSharpOptions) = |
115 | 127 | let inheritUnionEncoding (options: JsonFSharpOptions) = |
116 | 128 | if options.UnionEncoding.HasFlag(JsonUnionEncoding.Inherit) then |
117 | 129 | options.WithUnionEncoding(defaultOptions.UnionEncoding) |
118 | 130 | else |
119 | 131 | options |
120 | 132 |
|
121 | | - let applyAttributeOverride () = |
122 | | - if defaultOptions.AllowOverride then |
123 | | - match |
124 | | - ty.GetCustomAttributes(typeof<IJsonFSharpConverterAttribute>, true) |
125 | | - |> Array.tryHead |
126 | | - with |
127 | | - | Some (:? IJsonFSharpConverterAttribute as attr) -> attr.Options |> inheritUnionEncoding |
128 | | - | _ -> defaultOptions |
| 133 | + let overrides = defaultOptions.Overrides defaultOptions |
| 134 | + |
| 135 | + match tryGetTypeOrGeneric ty overrides with |
| 136 | + | ValueSome options -> |
| 137 | + inheritUnionEncoding options |
| 138 | + | ValueNone when defaultOptions.AllowOverride -> |
| 139 | + let attrs = ty.GetCustomAttributes(typeof<IJsonFSharpConverterAttribute>, true) |
| 140 | + if attrs.Length > 0 then |
| 141 | + let attr = attrs[0] :?> IJsonFSharpConverterAttribute |
| 142 | + inheritUnionEncoding attr.Options |
129 | 143 | else |
130 | 144 | defaultOptions |
131 | | - |
132 | | - let overrides = defaultOptions.Overrides defaultOptions |
133 | | - if isNull overrides then |
134 | | - applyAttributeOverride () |
135 | | - else |
136 | | - match overrides.TryGetValue(ty) with |
137 | | - | true, options -> options |> inheritUnionEncoding |
138 | | - | false, _ -> applyAttributeOverride () |
| 145 | + | ValueNone -> |
| 146 | + defaultOptions |
139 | 147 |
|
140 | 148 | let isWrappedString (ty: Type) = |
141 | 149 | TypeCache.isUnion ty |
|
0 commit comments