Skip to content

Improve detection of collection element type #1720

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions src/JsonApiDotNetCore.Annotations/CollectionConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,17 +104,26 @@ public IReadOnlyCollection<IIdentifiable> ExtractResources(object? value)
/// </summary>
public Type? FindCollectionElementType(Type? type)
{
if (type is { IsGenericType: true, GenericTypeArguments.Length: 1 })
if (type != null)
{
if (type.IsOrImplementsInterface<IEnumerable>())
Type? enumerableClosedType = IsEnumerableClosedType(type) ? type : null;
enumerableClosedType ??= type.GetInterfaces().FirstOrDefault(IsEnumerableClosedType);

if (enumerableClosedType != null)
{
return type.GenericTypeArguments[0];
return enumerableClosedType.GenericTypeArguments[0];
}
}

return null;
}

private static bool IsEnumerableClosedType(Type type)
{
bool isClosedType = type is { IsGenericType: true, ContainsGenericParameters: false };
return isClosedType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>);
}

/// <summary>
/// Indicates whether a <see cref="HashSet{T}" /> instance can be assigned to the specified type, for example:
/// <code><![CDATA[
Expand Down
12 changes: 2 additions & 10 deletions src/JsonApiDotNetCore/Configuration/ResourceGraphBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -396,8 +396,8 @@ private ReadOnlyCollection<EagerLoadAttribute> GetEagerLoads(Type resourceClrTyp
continue;
}

Type innerType = TypeOrElementType(property.PropertyType);
eagerLoad.Children = GetEagerLoads(innerType, recursionDepth + 1);
Type rightType = CollectionConverter.Instance.FindCollectionElementType(property.PropertyType) ?? property.PropertyType;
eagerLoad.Children = GetEagerLoads(rightType, recursionDepth + 1);
eagerLoad.Property = property;

eagerLoads.Add(eagerLoad);
Expand Down Expand Up @@ -459,14 +459,6 @@ private static void AssertNoInfiniteRecursion(int recursionDepth)
}
}

private Type TypeOrElementType(Type type)
{
Type[] interfaces = type.GetInterfaces().Where(@interface => @interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof(IEnumerable<>))
.ToArray();

return interfaces.Length == 1 ? interfaces.Single().GenericTypeArguments[0] : type;
}

private string FormatResourceName(Type resourceClrType)
{
var formatter = new ResourceNameFormatter(_options.SerializerOptions.PropertyNamingPolicy);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
using FluentAssertions;
using JsonApiDotNetCore;
using Xunit;

namespace JsonApiDotNetCoreTests.UnitTests.TypeConversion;

public sealed class CollectionConverterTests
{
[Fact]
public void Finds_element_type_for_generic_list()
{
// Arrange
Type sourceType = typeof(List<string>);

// Act
Type? elementType = CollectionConverter.Instance.FindCollectionElementType(sourceType);

// Assert
elementType.Should().Be<string>();
}

[Fact]
public void Finds_element_type_for_generic_enumerable()
{
// Arrange
Type sourceType = typeof(IEnumerable<string>);

// Act
Type? elementType = CollectionConverter.Instance.FindCollectionElementType(sourceType);

// Assert
elementType.Should().Be<string>();
}

[Fact]
public void Finds_element_type_for_custom_generic_collection_with_multiple_type_parameters()
{
// Arrange
Type sourceType = typeof(CustomCollection<int, string>);

// Act
Type? elementType = CollectionConverter.Instance.FindCollectionElementType(sourceType);

// Assert
elementType.Should().Be<string>();
}

[Fact]
public void Finds_element_type_for_custom_non_generic_collection()
{
// Arrange
Type sourceType = typeof(CustomCollectionOfIntString);

// Act
Type? elementType = CollectionConverter.Instance.FindCollectionElementType(sourceType);

// Assert
elementType.Should().Be<string>();
}

[Fact]
public void Finds_no_element_type_for_non_generic_type()
{
// Arrange
Type sourceType = typeof(int);

// Act
Type? elementType = CollectionConverter.Instance.FindCollectionElementType(sourceType);

// Assert
elementType.Should().BeNull();
}

[Fact]
public void Finds_no_element_type_for_non_collection_generic_type()
{
// Arrange
Type sourceType = typeof(Tuple<int, string>);

// Act
Type? elementType = CollectionConverter.Instance.FindCollectionElementType(sourceType);

// Assert
elementType.Should().BeNull();
}

[Fact]
public void Finds_no_element_type_for_unbound_generic_type()
{
// Arrange
Type sourceType = typeof(List<>);

// Act
Type? elementType = CollectionConverter.Instance.FindCollectionElementType(sourceType);

// Assert
elementType.Should().BeNull();
}

// ReSharper disable once UnusedTypeParameter
private class CustomCollection<TOther, TElement> : List<TElement>;

private sealed class CustomCollectionOfIntString : CustomCollection<int, string>;
}
Loading