From cf2ac05e92e5f3e922052385cea29ba92696836f Mon Sep 17 00:00:00 2001 From: Sipke Schoorstra Date: Thu, 6 Feb 2025 10:44:04 +0100 Subject: [PATCH] Refactor ArgumentJsonConverter to improve type handling. Enhanced type handling by distinguishing arrays, collections, and single types. Added support for "isCollection" metadata and adjusted serialization/deserialization logic to ensure accurate mapping of element types and aliases. This improves clarity and flexibility in JSON representation. --- .../Serialization/ArgumentJsonConverter.cs | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/modules/Elsa.Workflows.Api/Serialization/ArgumentJsonConverter.cs b/src/modules/Elsa.Workflows.Api/Serialization/ArgumentJsonConverter.cs index 81f5a0d42..fc829f41c 100644 --- a/src/modules/Elsa.Workflows.Api/Serialization/ArgumentJsonConverter.cs +++ b/src/modules/Elsa.Workflows.Api/Serialization/ArgumentJsonConverter.cs @@ -28,10 +28,18 @@ public class ArgumentJsonConverter : JsonConverter newOptions.Converters.RemoveWhere(x => x is ArgumentJsonConverterFactory); var jsonObject = (JsonObject)JsonSerializer.SerializeToNode(value, value.GetType(), newOptions)!; - var isArray = value.Type.IsCollectionType(); - jsonObject["isArray"] = isArray; - jsonObject["type"] = _wellKnownTypeRegistry.GetAliasOrDefault(isArray ? value.Type.GetCollectionElementType() : value.Type); - + var typeName = value.Type; + var typeAlias = _wellKnownTypeRegistry.TryGetAlias(typeName, out var alias) ? alias : null; + var isArray = typeName.IsArray; + var isCollection = typeName.IsCollectionType(); + var elementTypeName = isArray ? typeName.GetElementType() : isCollection ? typeName.GenericTypeArguments[0] : typeName; + var elementTypeAlias = _wellKnownTypeRegistry.GetAliasOrDefault(elementTypeName); + var finalTypeAlias = isArray || isCollection ? elementTypeAlias : typeAlias; + + if(isArray) jsonObject["isArray"] = isArray; + if(isCollection) jsonObject["isCollection"] = isCollection; + + jsonObject["type"] = finalTypeAlias; JsonSerializer.Serialize(writer, jsonObject, newOptions); } @@ -40,11 +48,12 @@ public class ArgumentJsonConverter : JsonConverter { var jsonObject = (JsonObject)JsonNode.Parse(ref reader)!; var isArray = jsonObject["isArray"]?.GetValue() ?? false; - var typeName = jsonObject["type"]!.GetValue(); - var type = _wellKnownTypeRegistry.GetTypeOrDefault(typeName); + var isCollection = jsonObject["isCollection"]?.GetValue() ?? false; + var typeAlias = jsonObject["type"]!.GetValue(); + var type = _wellKnownTypeRegistry.GetTypeOrDefault(typeAlias); - if (isArray) - type = type.MakeArrayType(); + if (isArray) type = type.MakeArrayType(); + if (isCollection) type = type.MakeGenericType(type.GenericTypeArguments[0]); var newOptions = new JsonSerializerOptions(options); newOptions.Converters.RemoveWhere(x => x is ArgumentJsonConverterFactory);