| | | 1 | | using System.Collections; |
| | | 2 | | using System.Dynamic; |
| | | 3 | | using System.Reflection; |
| | | 4 | | using System.Text.Json; |
| | | 5 | | using System.Text.Json.Nodes; |
| | | 6 | | using System.Text.Json.Serialization; |
| | | 7 | | using Elsa.Extensions; |
| | | 8 | | using Elsa.Workflows.Serialization.ReferenceHandlers; |
| | | 9 | | using Newtonsoft.Json.Linq; |
| | | 10 | | |
| | | 11 | | namespace Elsa.Workflows.Serialization.Converters; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Reads objects as primitive types rather than <see cref="JsonElement"/> values while also maintaining the .NET type n |
| | | 15 | | /// </summary> |
| | | 16 | | public class PolymorphicObjectConverter : JsonConverter<object> |
| | | 17 | | { |
| | | 18 | | private const string TypePropertyName = "_type"; |
| | | 19 | | private const string ItemsPropertyName = "_items"; |
| | | 20 | | private const string IslandPropertyName = "_island"; |
| | | 21 | | private const string IdPropertyName = "$id"; |
| | | 22 | | private const string RefPropertyName = "$ref"; |
| | | 23 | | private const string ValuesPropertyName = "$values"; |
| | | 24 | | |
| | | 25 | | /// <inheritdoc /> |
| | | 26 | | public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | | 27 | | { |
| | 20533 | 28 | | var newOptions = options.Clone(); |
| | | 29 | | |
| | 20533 | 30 | | if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) |
| | 13340 | 31 | | return ReadPrimitive(ref reader, newOptions); |
| | | 32 | | |
| | 7193 | 33 | | var targetType = ReadType(reader, options); |
| | 7193 | 34 | | if (targetType == null) |
| | 6771 | 35 | | return ReadObject(ref reader, newOptions); |
| | | 36 | | |
| | | 37 | | // If the target type is not an IEnumerable, or is a dictionary, deserialize the object directly. |
| | 422 | 38 | | var isEnumerable = typeof(IEnumerable).IsAssignableFrom(targetType); |
| | | 39 | | |
| | 422 | 40 | | if (!isEnumerable) |
| | | 41 | | { |
| | | 42 | | try |
| | | 43 | | { |
| | 257 | 44 | | return JsonSerializer.Deserialize(ref reader, targetType, newOptions)!; |
| | | 45 | | } |
| | 0 | 46 | | catch (Exception e) when (e is NotSupportedException or TargetException) |
| | | 47 | | { |
| | 0 | 48 | | return default!; |
| | | 49 | | } |
| | | 50 | | } |
| | | 51 | | |
| | | 52 | | // If the target type is a Newtonsoft.JObject, parse the JSON island. |
| | 165 | 53 | | var isNewtonsoftObject = targetType == typeof(JObject); |
| | | 54 | | |
| | 165 | 55 | | if (isNewtonsoftObject) |
| | | 56 | | { |
| | 0 | 57 | | var parsedModel = JsonElement.ParseValue(ref reader); |
| | 0 | 58 | | var newtonsoftJson = parsedModel.GetProperty(IslandPropertyName).GetString(); |
| | 0 | 59 | | return !string.IsNullOrWhiteSpace(newtonsoftJson) ? JObject.Parse(newtonsoftJson) : new JObject(); |
| | | 60 | | } |
| | | 61 | | |
| | | 62 | | // If the target type is a Newtonsoft.JArray, parse the JSON island. |
| | 165 | 63 | | var isNewtonsoftArray = targetType == typeof(JArray); |
| | | 64 | | |
| | 165 | 65 | | if (isNewtonsoftArray) |
| | | 66 | | { |
| | 0 | 67 | | var parsedModel = JsonElement.ParseValue(ref reader); |
| | 0 | 68 | | var newtonsoftJson = parsedModel.GetProperty(IslandPropertyName).GetString(); |
| | 0 | 69 | | return !string.IsNullOrWhiteSpace(newtonsoftJson) ? JArray.Parse(newtonsoftJson) : new JArray(); |
| | | 70 | | } |
| | | 71 | | |
| | | 72 | | // If the target type is a System.Text.JsonObject, parse the JSON island. |
| | 165 | 73 | | var isJsonObject = targetType == typeof(JsonObject); |
| | | 74 | | |
| | 165 | 75 | | if (isJsonObject) |
| | | 76 | | { |
| | 0 | 77 | | var parsedModel = JsonElement.ParseValue(ref reader); |
| | 0 | 78 | | var systemTextJson = parsedModel.GetProperty(IslandPropertyName).GetString(); |
| | 0 | 79 | | return !string.IsNullOrWhiteSpace(systemTextJson) ? JsonNode.Parse(systemTextJson)! : new JsonObject(); |
| | | 80 | | } |
| | | 81 | | |
| | 165 | 82 | | var isJsonArray = targetType == typeof(JsonArray); |
| | | 83 | | |
| | 165 | 84 | | if (isJsonArray) |
| | | 85 | | { |
| | 0 | 86 | | var parsedModel = JsonElement.ParseValue(ref reader); |
| | 0 | 87 | | var systemTextJson = parsedModel.GetProperty(IslandPropertyName).GetString(); |
| | 0 | 88 | | return !string.IsNullOrWhiteSpace(systemTextJson) ? JsonNode.Parse(systemTextJson)! : new JsonArray(); |
| | | 89 | | } |
| | | 90 | | |
| | 165 | 91 | | var isDictionary = typeof(IDictionary).IsAssignableFrom(targetType); |
| | 165 | 92 | | if (isDictionary) |
| | | 93 | | { |
| | | 94 | | // Remove the _type property name from the JSON, if any. |
| | 143 | 95 | | var parsedNode = JsonNode.Parse(ref reader)!; |
| | 286 | 96 | | if (parsedNode is JsonObject parsedModel) parsedModel.Remove(TypePropertyName); |
| | 143 | 97 | | return parsedNode.Deserialize(targetType, newOptions)!; |
| | | 98 | | } |
| | | 99 | | |
| | 22 | 100 | | var isCollection = typeof(ICollection).IsAssignableFrom(targetType); |
| | | 101 | | |
| | | 102 | | // Otherwise, deserialize the object as an array. |
| | 22 | 103 | | var elementType = targetType.IsArray |
| | 22 | 104 | | ? targetType.GetElementType() |
| | 22 | 105 | | : targetType.GenericTypeArguments.FirstOrDefault() ?? |
| | 22 | 106 | | (isCollection // Could be a class derived from Collection<T> or List<T>. |
| | 22 | 107 | | ? targetType.BaseType?.GenericTypeArguments[0] |
| | 22 | 108 | | : targetType.GenericTypeArguments.FirstOrDefault() |
| | 22 | 109 | | ?? typeof(object)); |
| | 22 | 110 | | if (elementType == null) |
| | 0 | 111 | | throw new InvalidOperationException($"Cannot determine the element type of array '{targetType}'."); |
| | | 112 | | |
| | 22 | 113 | | var model = JsonElement.ParseValue(ref reader); |
| | 22 | 114 | | var referenceResolver = (newOptions.ReferenceHandler as CrossScopedReferenceHandler)?.GetResolver(); |
| | | 115 | | |
| | 22 | 116 | | if (model.TryGetProperty(RefPropertyName, out var refProperty)) |
| | | 117 | | { |
| | 0 | 118 | | var refId = refProperty.GetString()!; |
| | 0 | 119 | | return referenceResolver?.ResolveReference(refId)!; |
| | | 120 | | } |
| | | 121 | | |
| | 22 | 122 | | var values = model.TryGetProperty(ItemsPropertyName, out var itemsProp) ? itemsProp.EnumerateArray().ToList() : |
| | 22 | 123 | | var id = model.TryGetProperty(IdPropertyName, out var idProp) ? idProp.GetString() : default; |
| | 22 | 124 | | var collection = targetType.IsArray ? Array.CreateInstance(elementType, values.Count) : Activator.CreateInstance |
| | 22 | 125 | | var index = 0; |
| | | 126 | | |
| | 22 | 127 | | if (id != null) |
| | 5 | 128 | | referenceResolver?.AddReference(id, collection); |
| | | 129 | | |
| | 22 | 130 | | var isHashSet = targetType.GenericTypeArguments.Length == 1 && typeof(ISet<>).MakeGenericType(targetType.Generic |
| | 22 | 131 | | var addSetMethod = targetType.GetMethod("Add", [elementType])!; |
| | | 132 | | |
| | 138 | 133 | | foreach (var element in values) |
| | | 134 | | { |
| | 47 | 135 | | var deserializedElement = JsonSerializer.Deserialize(JsonSerializer.Serialize(element), elementType, newOpti |
| | 47 | 136 | | if (collection is Array array) |
| | | 137 | | { |
| | 36 | 138 | | array.SetValue(deserializedElement, index++); |
| | | 139 | | } |
| | 11 | 140 | | else if (isHashSet) |
| | | 141 | | { |
| | 0 | 142 | | addSetMethod.Invoke(collection, [ |
| | 0 | 143 | | deserializedElement |
| | 0 | 144 | | ]); |
| | | 145 | | } |
| | 11 | 146 | | else if (collection is IList list) |
| | | 147 | | { |
| | 11 | 148 | | list.Add(deserializedElement); |
| | | 149 | | } |
| | | 150 | | } |
| | | 151 | | |
| | 22 | 152 | | return collection; |
| | 257 | 153 | | } |
| | | 154 | | |
| | | 155 | | /// <inheritdoc /> |
| | | 156 | | public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) |
| | | 157 | | { |
| | 9566 | 158 | | if (value == null!) |
| | | 159 | | { |
| | 91 | 160 | | writer.WriteNullValue(); |
| | 91 | 161 | | return; |
| | | 162 | | } |
| | | 163 | | |
| | 9475 | 164 | | var newOptions = options.Clone(); |
| | 9475 | 165 | | var type = value.GetType(); |
| | | 166 | | |
| | | 167 | | // If the type is a primitive type or an enumerable of a primitive type, serialize the value directly. |
| | | 168 | | bool IsPrimitive(Type valueType) |
| | | 169 | | { |
| | 9475 | 170 | | return type.IsPrimitive |
| | 9475 | 171 | | || valueType == typeof(string) |
| | 9475 | 172 | | || valueType == typeof(decimal) |
| | 9475 | 173 | | || valueType == typeof(DateTimeOffset) |
| | 9475 | 174 | | || valueType == typeof(DateTime) |
| | 9475 | 175 | | || valueType == typeof(DateOnly) |
| | 9475 | 176 | | || valueType == typeof(TimeOnly) |
| | 9475 | 177 | | || valueType == typeof(JsonElement) |
| | 9475 | 178 | | || valueType == typeof(Guid) |
| | 9475 | 179 | | || valueType == typeof(TimeSpan) |
| | 9475 | 180 | | || valueType == typeof(Uri) |
| | 9475 | 181 | | || valueType == typeof(Version) |
| | 9475 | 182 | | || valueType.IsEnum; |
| | | 183 | | } |
| | | 184 | | |
| | 9475 | 185 | | if (IsPrimitive(type)) |
| | | 186 | | { |
| | | 187 | | // Remove the converter so that we don't end up in an infinite loop. |
| | 13254 | 188 | | newOptions.Converters.RemoveWhere(x => x is PolymorphicObjectConverterFactory); |
| | | 189 | | |
| | | 190 | | // Serialize the value directly. |
| | 1110 | 191 | | JsonSerializer.Serialize(writer, value, newOptions); |
| | 1110 | 192 | | return; |
| | | 193 | | } |
| | | 194 | | |
| | | 195 | | // Special case for Newtonsoft.Json and System.Text.Json types. |
| | | 196 | | // Newtonsoft.Json types are not supported by the System.Text.Json serializer and should be written as a string |
| | | 197 | | // We include metadata about the type so that we can deserialize it later. |
| | 8365 | 198 | | if (type == typeof(JObject) || type == typeof(JArray) || type == typeof(JsonObject) || type == typeof(JsonArray) |
| | | 199 | | { |
| | 17 | 200 | | writer.WriteStartObject(); |
| | 17 | 201 | | writer.WriteString(IslandPropertyName, value.ToString()); |
| | 17 | 202 | | writer.WriteString(TypePropertyName, type.GetSimpleAssemblyQualifiedName()); |
| | 17 | 203 | | writer.WriteEndObject(); |
| | 17 | 204 | | return; |
| | | 205 | | } |
| | | 206 | | |
| | | 207 | | // Determine if the value is going to be serialized for the first time. |
| | | 208 | | // Later on, we need to know this information to determine if we need to write the type name or not, so that we |
| | 8348 | 209 | | var shouldWriteTypeField = true; |
| | 8348 | 210 | | var referenceResolver = (CustomPreserveReferenceResolver?)(newOptions.ReferenceHandler as CrossScopedReferenceHa |
| | | 211 | | |
| | 8348 | 212 | | if (referenceResolver != null) |
| | | 213 | | { |
| | 85 | 214 | | var exists = referenceResolver.HasReference(value); |
| | 85 | 215 | | shouldWriteTypeField = !exists; |
| | | 216 | | } |
| | | 217 | | |
| | | 218 | | // Before we serialize the value, check to see if it's an ExpandoObject. |
| | | 219 | | // If it is, we need to sanitize its property names, because they can contain invalid characters. |
| | 8348 | 220 | | if (value is ExpandoObject) |
| | | 221 | | { |
| | 0 | 222 | | var sanitized = new ExpandoObject(); |
| | 0 | 223 | | var dictionary = (IDictionary<string, object?>)sanitized; |
| | 0 | 224 | | var expando = (IDictionary<string, object?>)value; |
| | | 225 | | |
| | 0 | 226 | | foreach (var kvp in expando) |
| | | 227 | | { |
| | 0 | 228 | | var key = EscapeKey(kvp.Key); |
| | 0 | 229 | | dictionary[key] = kvp.Value; |
| | | 230 | | } |
| | | 231 | | |
| | 0 | 232 | | value = sanitized; |
| | | 233 | | } |
| | | 234 | | |
| | 8348 | 235 | | var jsonElement = JsonDocument.Parse(JsonSerializer.Serialize(value, type, newOptions)).RootElement; |
| | | 236 | | |
| | | 237 | | // If the value is a string, serialize it directly. |
| | 8348 | 238 | | if (jsonElement.ValueKind == JsonValueKind.String) |
| | | 239 | | { |
| | | 240 | | // Serialize the value directly. |
| | 0 | 241 | | JsonSerializer.Serialize(writer, jsonElement, newOptions); |
| | 0 | 242 | | return; |
| | | 243 | | } |
| | | 244 | | |
| | 8348 | 245 | | writer.WriteStartObject(); |
| | | 246 | | |
| | 8348 | 247 | | if (jsonElement.ValueKind == JsonValueKind.Array) |
| | | 248 | | { |
| | 758 | 249 | | writer.WritePropertyName(ItemsPropertyName); |
| | 758 | 250 | | jsonElement.WriteTo(writer); |
| | | 251 | | } |
| | | 252 | | else |
| | | 253 | | { |
| | 31575 | 254 | | foreach (var property in jsonElement.EnumerateObject().Where(property => !property.NameEquals(TypePropertyNa |
| | | 255 | | { |
| | 5465 | 256 | | writer.WritePropertyName(property.Name); |
| | 5465 | 257 | | property.Value.WriteTo(writer); |
| | | 258 | | } |
| | | 259 | | } |
| | | 260 | | |
| | 8348 | 261 | | if (type != typeof(ExpandoObject)) |
| | | 262 | | { |
| | 8348 | 263 | | if (shouldWriteTypeField) |
| | | 264 | | { |
| | 8348 | 265 | | if (newOptions.Converters.OfType<TypeJsonConverter>().FirstOrDefault() is { } typeJsonConverter) |
| | | 266 | | { |
| | 8348 | 267 | | writer.WritePropertyName(TypePropertyName); |
| | 8348 | 268 | | typeJsonConverter.Write(writer, type, newOptions); |
| | | 269 | | } |
| | | 270 | | else |
| | | 271 | | { |
| | 0 | 272 | | writer.WriteString(TypePropertyName, type.GetSimpleAssemblyQualifiedName()); |
| | | 273 | | } |
| | | 274 | | } |
| | | 275 | | } |
| | | 276 | | |
| | 8348 | 277 | | writer.WriteEndObject(); |
| | 8348 | 278 | | } |
| | | 279 | | |
| | | 280 | | private Type? ReadType(Utf8JsonReader reader, JsonSerializerOptions options) |
| | | 281 | | { |
| | 7193 | 282 | | if (reader.TokenType != JsonTokenType.StartObject) |
| | 1482 | 283 | | return null; |
| | | 284 | | |
| | 5711 | 285 | | reader.Read(); // Move to the first token inside the object. |
| | 5711 | 286 | | string? typeName = null; |
| | | 287 | | |
| | | 288 | | // Read while we haven't reached the end of the object. |
| | 27357 | 289 | | while (reader.TokenType != JsonTokenType.EndObject) |
| | | 290 | | { |
| | | 291 | | // If we find the _type property, read its value and break out of the loop. |
| | 22068 | 292 | | if (reader.TokenType == JsonTokenType.PropertyName && reader.ValueTextEquals(TypePropertyName)) |
| | | 293 | | { |
| | 422 | 294 | | reader.Read(); // Move to the value of the _type property |
| | 422 | 295 | | if (options.Converters.OfType<TypeJsonConverter>().FirstOrDefault() is { } typeJsonConverter) |
| | | 296 | | { |
| | 422 | 297 | | return typeJsonConverter.Read(ref reader, typeof(Type), options); |
| | | 298 | | } |
| | | 299 | | else |
| | | 300 | | { |
| | 0 | 301 | | typeName = reader.GetString(); |
| | | 302 | | } |
| | 0 | 303 | | break; |
| | | 304 | | } |
| | | 305 | | |
| | | 306 | | // Skip through nested objects and arrays. |
| | 21646 | 307 | | if (reader.TokenType is JsonTokenType.StartObject or JsonTokenType.StartArray) |
| | | 308 | | { |
| | 3495 | 309 | | var depth = 1; |
| | | 310 | | |
| | 20105 | 311 | | while (depth > 0 && reader.Read()) |
| | | 312 | | { |
| | 16610 | 313 | | switch (reader.TokenType) |
| | | 314 | | { |
| | | 315 | | case JsonTokenType.StartObject: |
| | | 316 | | case JsonTokenType.StartArray: |
| | 0 | 317 | | depth++; |
| | 0 | 318 | | break; |
| | | 319 | | |
| | | 320 | | case JsonTokenType.EndObject: |
| | | 321 | | case JsonTokenType.EndArray: |
| | 3495 | 322 | | depth--; |
| | | 323 | | break; |
| | | 324 | | } |
| | | 325 | | } |
| | | 326 | | } |
| | | 327 | | |
| | 21646 | 328 | | reader.Read(); // Move to the next token |
| | | 329 | | } |
| | | 330 | | |
| | | 331 | | // If we found the _type property, attempt to resolve the type. |
| | 5289 | 332 | | var targetType = typeName != null ? Type.GetType(typeName) : default; |
| | 0 | 333 | | return targetType; |
| | | 334 | | } |
| | | 335 | | |
| | | 336 | | private static object ReadPrimitive(ref Utf8JsonReader reader, JsonSerializerOptions options) |
| | | 337 | | { |
| | 13340 | 338 | | return (reader.TokenType switch |
| | 13340 | 339 | | { |
| | 309 | 340 | | JsonTokenType.True => true, |
| | 4724 | 341 | | JsonTokenType.False => false, |
| | 9711 | 342 | | JsonTokenType.Number when reader.TryGetInt64(out var l) => l, |
| | 2779 | 343 | | JsonTokenType.Number => reader.GetDouble(), |
| | 1961 | 344 | | JsonTokenType.String => reader.GetString(), |
| | 101 | 345 | | JsonTokenType.Null => null, |
| | 0 | 346 | | _ => throw new JsonException("Not a primitive type.") |
| | 13340 | 347 | | })!; |
| | | 348 | | } |
| | | 349 | | |
| | | 350 | | private object ReadObject(ref Utf8JsonReader reader, JsonSerializerOptions options) |
| | | 351 | | { |
| | 6771 | 352 | | switch (reader.TokenType) |
| | | 353 | | { |
| | | 354 | | case JsonTokenType.StartArray: |
| | | 355 | | { |
| | 1482 | 356 | | var list = new List<object>(); |
| | 1482 | 357 | | while (reader.Read()) |
| | | 358 | | { |
| | 1482 | 359 | | switch (reader.TokenType) |
| | | 360 | | { |
| | | 361 | | default: |
| | 0 | 362 | | list.Add(Read(ref reader, typeof(object), options)); |
| | 0 | 363 | | break; |
| | | 364 | | |
| | | 365 | | case JsonTokenType.EndArray: |
| | 1482 | 366 | | return list; |
| | | 367 | | } |
| | | 368 | | } |
| | | 369 | | |
| | 0 | 370 | | throw new JsonException(); |
| | | 371 | | } |
| | | 372 | | case JsonTokenType.StartObject: |
| | 5289 | 373 | | var dict = new ExpandoObject() as IDictionary<string, object>; |
| | 5289 | 374 | | var referenceResolver = (CustomPreserveReferenceResolver)(options.ReferenceHandler as CrossScopedReferen |
| | 15523 | 375 | | while (reader.Read()) |
| | | 376 | | { |
| | 15523 | 377 | | switch (reader.TokenType) |
| | | 378 | | { |
| | | 379 | | case JsonTokenType.EndObject: |
| | | 380 | | // If the object contains a single entry with a key of $ref, return the referenced object. |
| | 5289 | 381 | | if (dict.Count == 1 && dict.TryGetValue(RefPropertyName, out var referencedObject)) |
| | 0 | 382 | | return referencedObject; |
| | 5289 | 383 | | return dict; |
| | | 384 | | |
| | | 385 | | case JsonTokenType.PropertyName: |
| | 10234 | 386 | | var key = reader.GetString()!; |
| | 10234 | 387 | | reader.Read(); |
| | 10234 | 388 | | if (referenceResolver != null && key == RefPropertyName) |
| | | 389 | | { |
| | 0 | 390 | | var referenceId = reader.GetString(); |
| | 0 | 391 | | var reference = referenceResolver.ResolveReference(referenceId!); |
| | 0 | 392 | | dict.Add(key, reference); |
| | | 393 | | } |
| | 10234 | 394 | | else if (referenceResolver != null && key == IdPropertyName) |
| | | 395 | | { |
| | 0 | 396 | | var referenceId = reader.GetString()!; |
| | | 397 | | |
| | | 398 | | // Attempt to add the reference; if not found, we can ignore it and assume that the user |
| | 0 | 399 | | referenceResolver.TryAddReference(referenceId, dict); |
| | | 400 | | } |
| | | 401 | | else |
| | | 402 | | { |
| | 10234 | 403 | | var value = Read(ref reader, typeof(object), options); |
| | 10234 | 404 | | var unescapedKey = UnescapeKey(key); |
| | 10234 | 405 | | dict.Add(unescapedKey, value); |
| | | 406 | | } |
| | | 407 | | |
| | 10234 | 408 | | break; |
| | | 409 | | |
| | | 410 | | default: |
| | 0 | 411 | | throw new JsonException(); |
| | | 412 | | } |
| | | 413 | | } |
| | | 414 | | |
| | 0 | 415 | | throw new JsonException(); |
| | | 416 | | default: |
| | 0 | 417 | | throw new JsonException($"Unknown token {reader.TokenType}"); |
| | | 418 | | } |
| | | 419 | | } |
| | | 420 | | |
| | | 421 | | private string EscapeKey(string key) |
| | | 422 | | { |
| | 0 | 423 | | return key.Replace("$", @"\\$"); |
| | | 424 | | } |
| | | 425 | | |
| | | 426 | | private string UnescapeKey(string key) |
| | | 427 | | { |
| | 10234 | 428 | | return key.Replace(@"\\$", "$"); |
| | | 429 | | } |
| | | 430 | | } |