| | | 1 | | using System.Collections; |
| | | 2 | | using System.Collections.Concurrent; |
| | | 3 | | using System.Dynamic; |
| | | 4 | | using System.Reflection; |
| | | 5 | | using System.Text.Json; |
| | | 6 | | using System.Text.Json.Nodes; |
| | | 7 | | using System.Text.Json.Serialization; |
| | | 8 | | using Elsa.Extensions; |
| | | 9 | | using Elsa.Workflows.Serialization.ReferenceHandlers; |
| | | 10 | | using Newtonsoft.Json.Linq; |
| | | 11 | | using Elsa.Common.Serialization; |
| | | 12 | | using Microsoft.Extensions.Logging; |
| | | 13 | | |
| | | 14 | | namespace Elsa.Workflows.Serialization.Converters; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Reads objects as primitive types rather than <see cref="JsonElement"/> values while also maintaining the .NET type n |
| | | 18 | | /// </summary> |
| | | 19 | | public class PolymorphicObjectConverter : JsonConverter<object> |
| | | 20 | | { |
| | | 21 | | private const string TypePropertyName = "_type"; |
| | | 22 | | private const string ItemsPropertyName = "_items"; |
| | | 23 | | private const string IslandPropertyName = "_island"; |
| | | 24 | | private const string IdPropertyName = "$id"; |
| | | 25 | | private const string RefPropertyName = "$ref"; |
| | | 26 | | private const string ValuesPropertyName = "$values"; |
| | | 27 | | private readonly ISerializationTypeRegistry _workflowJsonTypeRegistry; |
| | | 28 | | private readonly ILogger? _logger; |
| | | 29 | | |
| | | 30 | | // Types already reported as having no alias. Append-only and bounded by the number of distinct payload types |
| | | 31 | | // the process ever serializes, so that the warning below is emitted once per type rather than once per write. |
| | 1 | 32 | | private static readonly ConcurrentDictionary<Type, byte> ReportedUnaliasedTypes = new(); |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Initializes a new instance of the <see cref="PolymorphicObjectConverter"/> class. |
| | | 36 | | /// </summary> |
| | 52091 | 37 | | public PolymorphicObjectConverter(ISerializationTypeRegistry workflowJsonTypeRegistry, ILogger? logger = null) |
| | | 38 | | { |
| | 52091 | 39 | | _workflowJsonTypeRegistry = workflowJsonTypeRegistry; |
| | 52091 | 40 | | _logger = logger; |
| | 52091 | 41 | | } |
| | | 42 | | |
| | | 43 | | /// <summary> |
| | | 44 | | /// Initializes a new instance of the <see cref="PolymorphicObjectConverter"/> class. |
| | | 45 | | /// </summary> |
| | 0 | 46 | | public PolymorphicObjectConverter() |
| | | 47 | | { |
| | 0 | 48 | | _workflowJsonTypeRegistry = SerializationTypeRegistry.CreateDefault(); |
| | 0 | 49 | | } |
| | | 50 | | |
| | | 51 | | /// <inheritdoc /> |
| | | 52 | | public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | | 53 | | { |
| | 36599 | 54 | | var newOptions = options.Clone(); |
| | | 55 | | |
| | 36599 | 56 | | if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) |
| | 23608 | 57 | | return ReadPrimitive(ref reader, newOptions); |
| | | 58 | | |
| | 12991 | 59 | | var targetType = ReadType(reader, options); |
| | 12988 | 60 | | if (targetType == null) |
| | 11510 | 61 | | return ReadObject(ref reader, newOptions); |
| | | 62 | | |
| | 1478 | 63 | | targetType = GetInstantiableTargetType(targetType); |
| | | 64 | | |
| | | 65 | | // If the target type is not an IEnumerable, or is a dictionary, deserialize the object directly. |
| | 1477 | 66 | | var isEnumerable = typeof(IEnumerable).IsAssignableFrom(targetType); |
| | | 67 | | |
| | 1477 | 68 | | if (!isEnumerable) |
| | | 69 | | { |
| | | 70 | | try |
| | | 71 | | { |
| | 720 | 72 | | return JsonSerializer.Deserialize(ref reader, targetType, newOptions)!; |
| | | 73 | | } |
| | 0 | 74 | | catch (Exception e) when (e is NotSupportedException or TargetException) |
| | | 75 | | { |
| | 0 | 76 | | return default!; |
| | | 77 | | } |
| | | 78 | | } |
| | | 79 | | |
| | | 80 | | // If the target type is a Newtonsoft.JObject, parse the JSON island. |
| | 757 | 81 | | var isNewtonsoftObject = targetType == typeof(JObject); |
| | | 82 | | |
| | 757 | 83 | | if (isNewtonsoftObject) |
| | | 84 | | { |
| | 1 | 85 | | var parsedModel = JsonElement.ParseValue(ref reader); |
| | 1 | 86 | | var newtonsoftJson = parsedModel.GetProperty(IslandPropertyName).GetString(); |
| | 1 | 87 | | return !string.IsNullOrWhiteSpace(newtonsoftJson) ? JObject.Parse(newtonsoftJson) : new JObject(); |
| | | 88 | | } |
| | | 89 | | |
| | | 90 | | // If the target type is a Newtonsoft.JArray, parse the JSON island. |
| | 756 | 91 | | var isNewtonsoftArray = targetType == typeof(JArray); |
| | | 92 | | |
| | 756 | 93 | | if (isNewtonsoftArray) |
| | | 94 | | { |
| | 1 | 95 | | var parsedModel = JsonElement.ParseValue(ref reader); |
| | 1 | 96 | | var newtonsoftJson = parsedModel.GetProperty(IslandPropertyName).GetString(); |
| | 1 | 97 | | return !string.IsNullOrWhiteSpace(newtonsoftJson) ? JArray.Parse(newtonsoftJson) : new JArray(); |
| | | 98 | | } |
| | | 99 | | |
| | | 100 | | // If the target type is a System.Text.JsonObject, parse the JSON island. |
| | 755 | 101 | | var isJsonObject = targetType == typeof(JsonObject); |
| | | 102 | | |
| | 755 | 103 | | if (isJsonObject) |
| | | 104 | | { |
| | 1 | 105 | | var parsedModel = JsonElement.ParseValue(ref reader); |
| | 1 | 106 | | var systemTextJson = parsedModel.GetProperty(IslandPropertyName).GetString(); |
| | 1 | 107 | | return !string.IsNullOrWhiteSpace(systemTextJson) ? JsonNode.Parse(systemTextJson)! : new JsonObject(); |
| | | 108 | | } |
| | | 109 | | |
| | 754 | 110 | | var isJsonArray = targetType == typeof(JsonArray); |
| | | 111 | | |
| | 754 | 112 | | if (isJsonArray) |
| | | 113 | | { |
| | 1 | 114 | | var parsedModel = JsonElement.ParseValue(ref reader); |
| | 1 | 115 | | var systemTextJson = parsedModel.GetProperty(IslandPropertyName).GetString(); |
| | 1 | 116 | | return !string.IsNullOrWhiteSpace(systemTextJson) ? JsonNode.Parse(systemTextJson)! : new JsonArray(); |
| | | 117 | | } |
| | | 118 | | |
| | 753 | 119 | | var isDictionary = typeof(IDictionary).IsAssignableFrom(targetType); |
| | 753 | 120 | | if (isDictionary) |
| | | 121 | | { |
| | | 122 | | // Remove the _type property name from the JSON, if any. |
| | 722 | 123 | | var parsedNode = JsonNode.Parse(ref reader)!; |
| | 1444 | 124 | | if (parsedNode is JsonObject parsedModel) parsedModel.Remove(TypePropertyName); |
| | 722 | 125 | | return parsedNode.Deserialize(targetType, newOptions)!; |
| | | 126 | | } |
| | | 127 | | |
| | 31 | 128 | | var isCollection = typeof(ICollection).IsAssignableFrom(targetType); |
| | | 129 | | |
| | | 130 | | // Otherwise, deserialize the object as an array. |
| | 31 | 131 | | var elementType = targetType.IsArray |
| | 31 | 132 | | ? targetType.GetElementType() |
| | 31 | 133 | | : targetType.GenericTypeArguments.FirstOrDefault() ?? |
| | 31 | 134 | | (isCollection // Could be a class derived from Collection<T> or List<T>. |
| | 31 | 135 | | ? targetType.BaseType?.GenericTypeArguments[0] |
| | 31 | 136 | | : targetType.GenericTypeArguments.FirstOrDefault() |
| | 31 | 137 | | ?? typeof(object)); |
| | 31 | 138 | | if (elementType == null) |
| | 0 | 139 | | throw new InvalidOperationException($"Cannot determine the element type of array '{targetType}'."); |
| | | 140 | | |
| | 31 | 141 | | var model = JsonElement.ParseValue(ref reader); |
| | 31 | 142 | | var referenceResolver = (newOptions.ReferenceHandler as CrossScopedReferenceHandler)?.GetResolver(); |
| | | 143 | | |
| | 31 | 144 | | if (model.TryGetProperty(RefPropertyName, out var refProperty)) |
| | | 145 | | { |
| | 0 | 146 | | var refId = refProperty.GetString()!; |
| | 0 | 147 | | return referenceResolver?.ResolveReference(refId)!; |
| | | 148 | | } |
| | | 149 | | |
| | 31 | 150 | | var values = model.TryGetProperty(ItemsPropertyName, out var itemsProp) ? itemsProp.EnumerateArray().ToList() : |
| | 31 | 151 | | var id = model.TryGetProperty(IdPropertyName, out var idProp) ? idProp.GetString() : default; |
| | 31 | 152 | | var collection = targetType.IsArray ? Array.CreateInstance(elementType, values.Count) : Activator.CreateInstance |
| | 31 | 153 | | var index = 0; |
| | | 154 | | |
| | 31 | 155 | | if (id != null) |
| | 5 | 156 | | referenceResolver?.AddReference(id, collection); |
| | | 157 | | |
| | 31 | 158 | | var isHashSet = targetType.GenericTypeArguments.Length == 1 && typeof(ISet<>).MakeGenericType(targetType.Generic |
| | 31 | 159 | | var addSetMethod = targetType.GetMethod("Add", [elementType])!; |
| | | 160 | | |
| | 168 | 161 | | foreach (var element in values) |
| | | 162 | | { |
| | 53 | 163 | | var deserializedElement = JsonSerializer.Deserialize(JsonSerializer.Serialize(element), elementType, newOpti |
| | 53 | 164 | | if (collection is Array array) |
| | | 165 | | { |
| | 36 | 166 | | array.SetValue(deserializedElement, index++); |
| | | 167 | | } |
| | 17 | 168 | | else if (isHashSet) |
| | | 169 | | { |
| | 1 | 170 | | addSetMethod.Invoke(collection, [ |
| | 1 | 171 | | deserializedElement |
| | 1 | 172 | | ]); |
| | | 173 | | } |
| | 16 | 174 | | else if (collection is IList list) |
| | | 175 | | { |
| | 16 | 176 | | list.Add(deserializedElement); |
| | | 177 | | } |
| | | 178 | | } |
| | | 179 | | |
| | 31 | 180 | | return collection; |
| | 720 | 181 | | } |
| | | 182 | | |
| | | 183 | | /// <inheritdoc /> |
| | | 184 | | public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) |
| | | 185 | | { |
| | 16317 | 186 | | if (value == null!) |
| | | 187 | | { |
| | 104 | 188 | | writer.WriteNullValue(); |
| | 104 | 189 | | return; |
| | | 190 | | } |
| | | 191 | | |
| | 16213 | 192 | | var newOptions = options.Clone(); |
| | 16213 | 193 | | var type = value.GetType(); |
| | | 194 | | |
| | | 195 | | // If the type is a primitive type or an enumerable of a primitive type, serialize the value directly. |
| | | 196 | | bool IsPrimitive(Type valueType) |
| | | 197 | | { |
| | 16213 | 198 | | return type.IsPrimitive |
| | 16213 | 199 | | || valueType == typeof(string) |
| | 16213 | 200 | | || valueType == typeof(decimal) |
| | 16213 | 201 | | || valueType == typeof(DateTimeOffset) |
| | 16213 | 202 | | || valueType == typeof(DateTime) |
| | 16213 | 203 | | || valueType == typeof(DateOnly) |
| | 16213 | 204 | | || valueType == typeof(TimeOnly) |
| | 16213 | 205 | | || valueType == typeof(JsonElement) |
| | 16213 | 206 | | || valueType == typeof(Guid) |
| | 16213 | 207 | | || valueType == typeof(TimeSpan) |
| | 16213 | 208 | | || valueType == typeof(Uri) |
| | 16213 | 209 | | || valueType == typeof(Version) |
| | 16213 | 210 | | || valueType.IsEnum; |
| | | 211 | | } |
| | | 212 | | |
| | 16213 | 213 | | if (IsPrimitive(type)) |
| | | 214 | | { |
| | | 215 | | // Remove the converter so that we don't end up in an infinite loop. |
| | 41282 | 216 | | newOptions.Converters.RemoveWhere(x => x is PolymorphicObjectConverterFactory); |
| | | 217 | | |
| | | 218 | | // Serialize the value directly. |
| | 3090 | 219 | | JsonSerializer.Serialize(writer, value, newOptions); |
| | 3090 | 220 | | return; |
| | | 221 | | } |
| | | 222 | | |
| | | 223 | | // Special case for Newtonsoft.Json and System.Text.Json types. |
| | | 224 | | // Newtonsoft.Json types are not supported by the System.Text.Json serializer and should be written as a string |
| | | 225 | | // We include metadata about the type so that we can deserialize it later. |
| | 13123 | 226 | | if (type == typeof(JObject) || type == typeof(JArray) || type == typeof(JsonObject) || type == typeof(JsonArray) |
| | | 227 | | { |
| | 21 | 228 | | writer.WriteStartObject(); |
| | 21 | 229 | | writer.WriteString(IslandPropertyName, value.ToString()); |
| | 21 | 230 | | WriteTypeMetadata(writer, type); |
| | 21 | 231 | | writer.WriteEndObject(); |
| | 21 | 232 | | return; |
| | | 233 | | } |
| | | 234 | | |
| | | 235 | | // Determine if the value is going to be serialized for the first time. |
| | | 236 | | // Later on, we need to know this information to determine if we need to write the type name or not, so that we |
| | 13102 | 237 | | var shouldWriteTypeField = true; |
| | 13102 | 238 | | var referenceResolver = (CustomPreserveReferenceResolver?)(newOptions.ReferenceHandler as CrossScopedReferenceHa |
| | | 239 | | |
| | 13102 | 240 | | if (referenceResolver != null) |
| | | 241 | | { |
| | 132 | 242 | | var exists = referenceResolver.HasReference(value); |
| | 132 | 243 | | shouldWriteTypeField = !exists; |
| | | 244 | | } |
| | | 245 | | |
| | | 246 | | // Before we serialize the value, check to see if it's an ExpandoObject. |
| | | 247 | | // If it is, we need to sanitize its property names, because they can contain invalid characters. |
| | 13102 | 248 | | if (value is ExpandoObject) |
| | | 249 | | { |
| | 0 | 250 | | var sanitized = new ExpandoObject(); |
| | 0 | 251 | | var dictionary = (IDictionary<string, object?>)sanitized; |
| | 0 | 252 | | var expando = (IDictionary<string, object?>)value; |
| | | 253 | | |
| | 0 | 254 | | foreach (var kvp in expando) |
| | | 255 | | { |
| | 0 | 256 | | var key = EscapeKey(kvp.Key); |
| | 0 | 257 | | dictionary[key] = kvp.Value; |
| | | 258 | | } |
| | | 259 | | |
| | 0 | 260 | | value = sanitized; |
| | | 261 | | } |
| | | 262 | | |
| | 13102 | 263 | | var jsonElement = JsonDocument.Parse(JsonSerializer.Serialize(value, type, newOptions)).RootElement; |
| | | 264 | | |
| | | 265 | | // If the value is a string, serialize it directly. |
| | 13102 | 266 | | if (jsonElement.ValueKind == JsonValueKind.String) |
| | | 267 | | { |
| | | 268 | | // Serialize the value directly. |
| | 0 | 269 | | JsonSerializer.Serialize(writer, jsonElement, newOptions); |
| | 0 | 270 | | return; |
| | | 271 | | } |
| | | 272 | | |
| | | 273 | | // If the value was serialized as a primitive by another converter, |
| | | 274 | | // write it directly instead of assuming an object structure. |
| | 13102 | 275 | | if (jsonElement.ValueKind != JsonValueKind.Object && |
| | 13102 | 276 | | jsonElement.ValueKind != JsonValueKind.Array) |
| | | 277 | | { |
| | 0 | 278 | | jsonElement.WriteTo(writer); |
| | 0 | 279 | | return; |
| | | 280 | | } |
| | | 281 | | |
| | 13102 | 282 | | writer.WriteStartObject(); |
| | | 283 | | |
| | 13102 | 284 | | if (jsonElement.ValueKind == JsonValueKind.Array) |
| | | 285 | | { |
| | 741 | 286 | | writer.WritePropertyName(ItemsPropertyName); |
| | 741 | 287 | | jsonElement.WriteTo(writer); |
| | | 288 | | } |
| | | 289 | | else |
| | | 290 | | { |
| | 86882 | 291 | | foreach (var property in jsonElement.EnumerateObject().Where(property => !property.NameEquals(TypePropertyNa |
| | | 292 | | { |
| | 20720 | 293 | | writer.WritePropertyName(property.Name); |
| | 20720 | 294 | | property.Value.WriteTo(writer); |
| | | 295 | | } |
| | | 296 | | } |
| | | 297 | | |
| | 13102 | 298 | | if (type != typeof(ExpandoObject)) |
| | | 299 | | { |
| | 13102 | 300 | | if (shouldWriteTypeField) |
| | 13102 | 301 | | WriteTypeMetadata(writer, type); |
| | | 302 | | } |
| | | 303 | | |
| | 13102 | 304 | | writer.WriteEndObject(); |
| | 13102 | 305 | | } |
| | | 306 | | |
| | | 307 | | private Type? ReadType(Utf8JsonReader reader, JsonSerializerOptions options) |
| | | 308 | | { |
| | 12991 | 309 | | if (reader.TokenType != JsonTokenType.StartObject) |
| | 2137 | 310 | | return null; |
| | | 311 | | |
| | 10854 | 312 | | reader.Read(); // Move to the first token inside the object. |
| | 10854 | 313 | | string? typeName = null; |
| | | 314 | | |
| | | 315 | | // Read while we haven't reached the end of the object. |
| | 50282 | 316 | | while (reader.TokenType != JsonTokenType.EndObject) |
| | | 317 | | { |
| | | 318 | | // If we find the _type property, read its value and break out of the loop. |
| | 40909 | 319 | | if (reader.TokenType == JsonTokenType.PropertyName && reader.ValueTextEquals(TypePropertyName)) |
| | | 320 | | { |
| | 1481 | 321 | | reader.Read(); // Move to the value of the _type property |
| | 1481 | 322 | | if (options.Converters.OfType<TypeJsonConverter>().FirstOrDefault() is { } typeJsonConverter) |
| | | 323 | | { |
| | 1480 | 324 | | return typeJsonConverter.Read(ref reader, typeof(Type), options); |
| | | 325 | | } |
| | | 326 | | else |
| | | 327 | | { |
| | 1 | 328 | | typeName = reader.GetString(); |
| | | 329 | | } |
| | 1 | 330 | | break; |
| | | 331 | | } |
| | | 332 | | |
| | | 333 | | // Skip through nested objects and arrays. |
| | 39428 | 334 | | if (reader.TokenType is JsonTokenType.StartObject or JsonTokenType.StartArray) |
| | | 335 | | { |
| | 5968 | 336 | | var depth = 1; |
| | | 337 | | |
| | 33641 | 338 | | while (depth > 0 && reader.Read()) |
| | | 339 | | { |
| | 27673 | 340 | | switch (reader.TokenType) |
| | | 341 | | { |
| | | 342 | | case JsonTokenType.StartObject: |
| | | 343 | | case JsonTokenType.StartArray: |
| | 0 | 344 | | depth++; |
| | 0 | 345 | | break; |
| | | 346 | | |
| | | 347 | | case JsonTokenType.EndObject: |
| | | 348 | | case JsonTokenType.EndArray: |
| | 5968 | 349 | | depth--; |
| | | 350 | | break; |
| | | 351 | | } |
| | | 352 | | } |
| | | 353 | | } |
| | | 354 | | |
| | 39428 | 355 | | reader.Read(); // Move to the next token |
| | | 356 | | } |
| | | 357 | | |
| | | 358 | | // If we found the _type property, attempt to resolve the type. |
| | 9374 | 359 | | return typeName != null ? SerializationTypeResolver.ResolveType(_workflowJsonTypeRegistry, typeName) : default; |
| | | 360 | | } |
| | | 361 | | |
| | | 362 | | private void WriteTypeMetadata(Utf8JsonWriter writer, Type type) |
| | | 363 | | { |
| | 13123 | 364 | | if (!SerializationTypeResolver.TryGetAlias(_workflowJsonTypeRegistry, type, out var typeAlias)) |
| | | 365 | | { |
| | 2804 | 366 | | WarnAboutUnaliasedType(type); |
| | 2804 | 367 | | return; |
| | | 368 | | } |
| | | 369 | | |
| | 10319 | 370 | | writer.WritePropertyName(TypePropertyName); |
| | 10319 | 371 | | writer.WriteStringValue(typeAlias); |
| | 10319 | 372 | | } |
| | | 373 | | |
| | | 374 | | /// <summary> |
| | | 375 | | /// Warns that <paramref name="type"/> has no registered alias, which is not an error but is lossy: without an |
| | | 376 | | /// alias no <c>_type</c> discriminator is written, so on read there is no target type to deserialize into and |
| | | 377 | | /// the value comes back as an <see cref="ExpandoObject"/> whose keys carry the serializer's camel-case naming |
| | | 378 | | /// policy rather than the property names as they were authored. |
| | | 379 | | /// </summary> |
| | | 380 | | private void WarnAboutUnaliasedType(Type type) |
| | | 381 | | { |
| | | 382 | | // Check the level before claiming the once-per-type slot: claiming it first would spend the type's single |
| | | 383 | | // report on a call that logs nothing, and the type would then stay silent if the level is raised later. |
| | 2804 | 384 | | if (_logger == null || !_logger.IsEnabled(LogLevel.Warning) || !ReportedUnaliasedTypes.TryAdd(type, 0)) |
| | 2803 | 385 | | return; |
| | | 386 | | |
| | 1 | 387 | | _logger.LogWarning( |
| | 1 | 388 | | "Value of type {PayloadType} has no registered serialization alias, so it is stored without a type discrimin |
| | 1 | 389 | | "Register it during startup with AddTypeAlias<{PayloadTypeName}>(), or use a Dictionary<string, object> if a |
| | 1 | 390 | | type, |
| | 1 | 391 | | type, |
| | 1 | 392 | | type.Name); |
| | 1 | 393 | | } |
| | | 394 | | |
| | | 395 | | private static Type GetInstantiableTargetType(Type targetType) |
| | | 396 | | { |
| | 1478 | 397 | | if (targetType.ContainsGenericParameters) |
| | 0 | 398 | | throw new JsonException($"Workflow JSON type alias resolved to open generic type '{targetType}'."); |
| | | 399 | | |
| | 1478 | 400 | | if (!targetType.IsInterface && !targetType.IsAbstract) |
| | 1471 | 401 | | return targetType; |
| | | 402 | | |
| | 7 | 403 | | if (SerializationTypeResolver.TryGetInstantiableCollectionType(targetType, out var instantiableCollectionType)) |
| | 6 | 404 | | return instantiableCollectionType; |
| | | 405 | | |
| | 1 | 406 | | throw new JsonException($"Workflow JSON type alias resolved to non-instantiable type '{targetType}'."); |
| | | 407 | | } |
| | | 408 | | |
| | | 409 | | private static object ReadPrimitive(ref Utf8JsonReader reader, JsonSerializerOptions options) |
| | | 410 | | { |
| | 23608 | 411 | | return (reader.TokenType switch |
| | 23608 | 412 | | { |
| | 411 | 413 | | JsonTokenType.True => true, |
| | 8162 | 414 | | JsonTokenType.False => false, |
| | 15383 | 415 | | JsonTokenType.Number when reader.TryGetInt64(out var l) => l, |
| | 4529 | 416 | | JsonTokenType.Number => reader.GetDouble(), |
| | 4902 | 417 | | JsonTokenType.String => reader.GetString(), |
| | 177 | 418 | | JsonTokenType.Null => null, |
| | 0 | 419 | | _ => throw new JsonException("Not a primitive type.") |
| | 23608 | 420 | | })!; |
| | | 421 | | } |
| | | 422 | | |
| | | 423 | | private object ReadObject(ref Utf8JsonReader reader, JsonSerializerOptions options) |
| | | 424 | | { |
| | 11510 | 425 | | switch (reader.TokenType) |
| | | 426 | | { |
| | | 427 | | case JsonTokenType.StartArray: |
| | | 428 | | { |
| | 2137 | 429 | | var list = new List<object>(); |
| | 2137 | 430 | | while (reader.Read()) |
| | | 431 | | { |
| | 2137 | 432 | | switch (reader.TokenType) |
| | | 433 | | { |
| | | 434 | | default: |
| | 0 | 435 | | list.Add(Read(ref reader, typeof(object), options)); |
| | 0 | 436 | | break; |
| | | 437 | | |
| | | 438 | | case JsonTokenType.EndArray: |
| | 2137 | 439 | | return list; |
| | | 440 | | } |
| | | 441 | | } |
| | | 442 | | |
| | 0 | 443 | | throw new JsonException(); |
| | | 444 | | } |
| | | 445 | | case JsonTokenType.StartObject: |
| | 9373 | 446 | | var dict = new ExpandoObject() as IDictionary<string, object>; |
| | 9373 | 447 | | var referenceResolver = (CustomPreserveReferenceResolver)(options.ReferenceHandler as CrossScopedReferen |
| | 26980 | 448 | | while (reader.Read()) |
| | | 449 | | { |
| | 26980 | 450 | | switch (reader.TokenType) |
| | | 451 | | { |
| | | 452 | | case JsonTokenType.EndObject: |
| | | 453 | | // If the object contains a single entry with a key of $ref, return the referenced object. |
| | 9373 | 454 | | if (dict.Count == 1 && dict.TryGetValue(RefPropertyName, out var referencedObject)) |
| | 0 | 455 | | return referencedObject; |
| | 9373 | 456 | | return dict; |
| | | 457 | | |
| | | 458 | | case JsonTokenType.PropertyName: |
| | 17607 | 459 | | var key = reader.GetString()!; |
| | 17607 | 460 | | reader.Read(); |
| | 17607 | 461 | | if (referenceResolver != null && key == RefPropertyName) |
| | | 462 | | { |
| | 0 | 463 | | var referenceId = reader.GetString(); |
| | 0 | 464 | | var reference = referenceResolver.ResolveReference(referenceId!); |
| | 0 | 465 | | dict.Add(key, reference); |
| | | 466 | | } |
| | 17607 | 467 | | else if (referenceResolver != null && key == IdPropertyName) |
| | | 468 | | { |
| | 1 | 469 | | var referenceId = reader.GetString()!; |
| | | 470 | | |
| | | 471 | | // Attempt to add the reference; if not found, we can ignore it and assume that the user |
| | 1 | 472 | | referenceResolver.TryAddReference(referenceId, dict); |
| | | 473 | | } |
| | | 474 | | else |
| | | 475 | | { |
| | 17606 | 476 | | var value = Read(ref reader, typeof(object), options); |
| | 17606 | 477 | | var unescapedKey = UnescapeKey(key); |
| | 17606 | 478 | | dict.Add(unescapedKey, value); |
| | | 479 | | } |
| | | 480 | | |
| | 17606 | 481 | | break; |
| | | 482 | | |
| | | 483 | | default: |
| | 0 | 484 | | throw new JsonException(); |
| | | 485 | | } |
| | | 486 | | } |
| | | 487 | | |
| | 0 | 488 | | throw new JsonException(); |
| | | 489 | | default: |
| | 0 | 490 | | throw new JsonException($"Unknown token {reader.TokenType}"); |
| | | 491 | | } |
| | | 492 | | } |
| | | 493 | | |
| | | 494 | | private string EscapeKey(string key) |
| | | 495 | | { |
| | 0 | 496 | | return key.Replace("$", @"\\$"); |
| | | 497 | | } |
| | | 498 | | |
| | | 499 | | private string UnescapeKey(string key) |
| | | 500 | | { |
| | 17606 | 501 | | return key.Replace(@"\\$", "$"); |
| | | 502 | | } |
| | | 503 | | } |