forked from domaindrivendev/Swashbuckle.AspNetCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNewtonsoftDataContractResolver.cs
More file actions
232 lines (200 loc) · 10.5 KB
/
Copy pathNewtonsoftDataContractResolver.cs
File metadata and controls
232 lines (200 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace Swashbuckle.AspNetCore.Newtonsoft;
public class NewtonsoftDataContractResolver(JsonSerializerSettings serializerSettings) : ISerializerDataContractResolver
{
private readonly JsonSerializerSettings _serializerSettings = serializerSettings;
private readonly IContractResolver _contractResolver = serializerSettings.ContractResolver ?? new DefaultContractResolver();
public DataContract GetDataContractForType(Type type)
{
var effectiveType = Nullable.GetUnderlyingType(type) ?? type;
if (effectiveType.IsOneOf(typeof(object), typeof(JToken), typeof(JObject), typeof(JArray)))
{
return DataContract.ForDynamic(
underlyingType: effectiveType,
jsonConverter: JsonConverterFunc);
}
var jsonContract = _contractResolver.ResolveContract(type);
var effectiveUnderlyingType = Nullable.GetUnderlyingType(jsonContract.UnderlyingType) ?? jsonContract.UnderlyingType;
if (jsonContract is JsonPrimitiveContract && !effectiveUnderlyingType.IsEnum)
{
if (!PrimitiveTypesAndFormats.TryGetValue(effectiveUnderlyingType, out var primitiveTypeAndFormat))
{
primitiveTypeAndFormat = Tuple.Create(DataType.String, (string)null);
}
return DataContract.ForPrimitive(
underlyingType: jsonContract.UnderlyingType,
dataType: primitiveTypeAndFormat.Item1,
dataFormat: primitiveTypeAndFormat.Item2,
jsonConverter: JsonConverterFunc);
}
if (jsonContract is JsonPrimitiveContract && effectiveUnderlyingType.IsEnum)
{
var enumValues = effectiveUnderlyingType.GetEnumValues();
// Test to determine if the serializer will treat as string
var serializeAsString = (enumValues.Length > 0) &&
#if NET
JsonConverterFunc(enumValues.GetValue(0)).StartsWith('\"');
#else
JsonConverterFunc(enumValues.GetValue(0)).StartsWith("\"");
#endif
var primitiveTypeAndFormat = serializeAsString
? PrimitiveTypesAndFormats[typeof(string)]
: PrimitiveTypesAndFormats[effectiveUnderlyingType.GetEnumUnderlyingType()];
return DataContract.ForPrimitive(
underlyingType: jsonContract.UnderlyingType,
dataType: primitiveTypeAndFormat.Item1,
dataFormat: primitiveTypeAndFormat.Item2,
jsonConverter: JsonConverterFunc);
}
if (jsonContract is JsonArrayContract jsonArrayContract)
{
return DataContract.ForArray(
underlyingType: jsonArrayContract.UnderlyingType,
itemType: jsonArrayContract.CollectionItemType ?? typeof(object),
jsonConverter: JsonConverterFunc);
}
if (jsonContract is JsonDictionaryContract jsonDictionaryContract)
{
var keyType = jsonDictionaryContract.DictionaryKeyType ?? typeof(object);
var valueType = jsonDictionaryContract.DictionaryValueType ?? typeof(object);
IEnumerable<string> keys = null;
if (keyType.IsEnum)
{
// This is a special case where we know the possible key values
var enumValuesAsJson = keyType.GetEnumValues()
.Cast<object>()
.Select(JsonConverterFunc);
keys =
#if NET
enumValuesAsJson.Any(json => json.StartsWith('\"'))
#else
enumValuesAsJson.Any(json => json.StartsWith("\""))
#endif
? enumValuesAsJson.Select(json => json.Replace("\"", string.Empty))
: keyType.GetEnumNames();
}
return DataContract.ForDictionary(
underlyingType: jsonDictionaryContract.UnderlyingType,
valueType: valueType,
keys: keys,
jsonConverter: JsonConverterFunc);
}
if (jsonContract is JsonObjectContract jsonObjectContract)
{
// This handles DateOnly and TimeOnly
if (PrimitiveTypesAndFormats.TryGetValue(jsonContract.UnderlyingType, out var primitiveTypeAndFormat))
{
return DataContract.ForPrimitive(
underlyingType: jsonContract.UnderlyingType,
dataType: primitiveTypeAndFormat.Item1,
dataFormat: primitiveTypeAndFormat.Item2,
jsonConverter: JsonConverterFunc);
}
string typeNameProperty = null;
string typeNameValue = null;
if (_serializerSettings.TypeNameHandling == TypeNameHandling.Objects ||
_serializerSettings.TypeNameHandling == TypeNameHandling.All ||
_serializerSettings.TypeNameHandling == TypeNameHandling.Auto)
{
typeNameProperty = "$type";
typeNameValue = (_serializerSettings.TypeNameAssemblyFormatHandling == TypeNameAssemblyFormatHandling.Full)
? jsonObjectContract.UnderlyingType.AssemblyQualifiedName
: $"{jsonObjectContract.UnderlyingType.FullName}, {jsonObjectContract.UnderlyingType.Assembly.GetName().Name}";
}
return DataContract.ForObject(
underlyingType: jsonObjectContract.UnderlyingType,
properties: GetDataPropertiesFor(jsonObjectContract, out Type extensionDataType),
extensionDataType: extensionDataType,
typeNameProperty: typeNameProperty,
typeNameValue: typeNameValue,
jsonConverter: JsonConverterFunc);
}
return DataContract.ForDynamic(
underlyingType: effectiveType,
jsonConverter: JsonConverterFunc);
}
private string JsonConverterFunc(object value)
=> JsonConvert.SerializeObject(value, _serializerSettings);
private List<DataProperty> GetDataPropertiesFor(JsonObjectContract jsonObjectContract, out Type extensionDataType)
{
var dataProperties = new List<DataProperty>();
foreach (var jsonProperty in jsonObjectContract.Properties)
{
bool memberInfoIsObtained = jsonProperty.TryGetMemberInfo(out MemberInfo memberInfo);
if (jsonProperty.Ignored || (memberInfoIsObtained && memberInfo.CustomAttributes.Any(t => t.AttributeType == typeof(SwaggerIgnoreAttribute))))
{
continue;
}
var required = jsonProperty.IsRequiredSpecified()
? jsonProperty.Required
: jsonObjectContract.ItemRequired ?? Required.Default;
var isSetViaConstructor = jsonProperty.DeclaringType != null && jsonProperty.DeclaringType.GetConstructors()
.SelectMany(c => c.GetParameters())
.Any(p =>
{
// Newtonsoft supports setting via constructor if either underlying OR JSON names match
return
string.Equals(p.Name, jsonProperty.UnderlyingName, StringComparison.OrdinalIgnoreCase) ||
string.Equals(p.Name, jsonProperty.PropertyName, StringComparison.OrdinalIgnoreCase);
});
dataProperties.Add(
new DataProperty(
name: jsonProperty.PropertyName,
isRequired: required == Required.Always || required == Required.AllowNull,
isNullable: (required == Required.AllowNull || required == Required.Default) && jsonProperty.PropertyType.IsReferenceOrNullableType(),
isReadOnly: jsonProperty.Readable && !jsonProperty.Writable && !isSetViaConstructor,
isWriteOnly: jsonProperty.Writable && !jsonProperty.Readable,
memberType: jsonProperty.PropertyType,
memberInfo: memberInfo));
}
extensionDataType = jsonObjectContract.ExtensionDataValueType;
#if NET
// If applicable, honor ProblemDetailsConverter
if (jsonObjectContract.UnderlyingType.IsAssignableTo(typeof(Microsoft.AspNetCore.Mvc.ProblemDetails))
&& _serializerSettings.Converters.OfType<Microsoft.AspNetCore.Mvc.NewtonsoftJson.ProblemDetailsConverter>().Any())
{
var extensionsProperty = dataProperties.FirstOrDefault(p => p.MemberInfo.Name == "Extensions");
if (extensionsProperty != null)
{
dataProperties.Remove(extensionsProperty);
extensionDataType = typeof(object);
}
}
#endif
return dataProperties;
}
private static readonly Dictionary<Type, Tuple<DataType, string>> PrimitiveTypesAndFormats = new()
{
[typeof(bool)] = Tuple.Create(DataType.Boolean, (string)null),
[typeof(byte)] = Tuple.Create(DataType.Integer, "int32"),
[typeof(sbyte)] = Tuple.Create(DataType.Integer, "int32"),
[typeof(short)] = Tuple.Create(DataType.Integer, "int32"),
[typeof(ushort)] = Tuple.Create(DataType.Integer, "int32"),
[typeof(int)] = Tuple.Create(DataType.Integer, "int32"),
[typeof(uint)] = Tuple.Create(DataType.Integer, "int32"),
[typeof(long)] = Tuple.Create(DataType.Integer, "int64"),
[typeof(ulong)] = Tuple.Create(DataType.Integer, "int64"),
[typeof(float)] = Tuple.Create(DataType.Number, "float"),
[typeof(double)] = Tuple.Create(DataType.Number, "double"),
[typeof(decimal)] = Tuple.Create(DataType.Number, "double"),
[typeof(byte[])] = Tuple.Create(DataType.String, "byte"),
[typeof(string)] = Tuple.Create(DataType.String, (string)null),
[typeof(char)] = Tuple.Create(DataType.String, (string)null),
[typeof(DateTime)] = Tuple.Create(DataType.String, "date-time"),
[typeof(DateTimeOffset)] = Tuple.Create(DataType.String, "date-time"),
[typeof(Guid)] = Tuple.Create(DataType.String, "uuid"),
[typeof(Uri)] = Tuple.Create(DataType.String, "uri"),
[typeof(TimeSpan)] = Tuple.Create(DataType.String, "date-span"),
#if NET
[typeof(DateOnly)] = Tuple.Create(DataType.String, "date"),
[typeof(TimeOnly)] = Tuple.Create(DataType.String, "time"),
[typeof(Int128)] = Tuple.Create(DataType.Integer, "int128"),
[typeof(UInt128)] = Tuple.Create(DataType.Integer, "int128"),
#endif
};
}