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.
This commit is contained in:
Sipke Schoorstra 2025-02-06 10:44:04 +01:00
parent bce31b649d
commit cf2ac05e92

View file

@ -28,10 +28,18 @@ public class ArgumentJsonConverter : JsonConverter<ArgumentDefinition>
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<ArgumentDefinition>
{
var jsonObject = (JsonObject)JsonNode.Parse(ref reader)!;
var isArray = jsonObject["isArray"]?.GetValue<bool>() ?? false;
var typeName = jsonObject["type"]!.GetValue<string>();
var type = _wellKnownTypeRegistry.GetTypeOrDefault(typeName);
var isCollection = jsonObject["isCollection"]?.GetValue<bool>() ?? false;
var typeAlias = jsonObject["type"]!.GetValue<string>();
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);