Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit aea175c

Browse files
committed
Add support for coercing into inherited List<T>
1 parent 024ceeb commit aea175c

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/ServiceStack.Text/CsvSerializer.cs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,8 @@ public static object DeserializeFromStream(Type type, Stream stream)
150150
public static T DeserializeFromString<T>(string text)
151151
{
152152
if (string.IsNullOrEmpty(text)) return default(T);
153-
return (T)CsvSerializer<T>.ReadObject(text);
153+
var results = CsvSerializer<T>.ReadObject(text);
154+
return CsvSerializer<T>.ConvertFrom(results);
154155
}
155156

156157
public static object DeserializeFromString(Type type, string text)
@@ -482,5 +483,29 @@ public static object ReadObject(string value)
482483
}
483484
}
484485

486+
public static T ConvertFrom(object results)
487+
{
488+
if (typeof(T).IsAssignableFromType(results.GetType()))
489+
{
490+
return (T)results;
491+
}
492+
493+
foreach (var ci in typeof(T).GetConstructors())
494+
{
495+
var ciParams = ci.GetParameters();
496+
if (ciParams.Length == 1)
497+
{
498+
var pi = ciParams.First();
499+
if (pi.ParameterType.IsAssignableFromType(typeof(T)))
500+
{
501+
var to = ci.Invoke(new[] { results });
502+
return (T)to;
503+
}
504+
}
505+
}
506+
507+
return results.ConvertTo<T>();
508+
}
509+
485510
}
486511
}

tests/ServiceStack.Text.Tests/CsvSerializerTests.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,12 @@ public void Can_Serialize_Movies()
9595
SerializeAndDeserialize(MoviesData.Movies);
9696
}
9797

98+
[Test]
99+
public void Can_Serialize_inherited_Movies()
100+
{
101+
SerializeAndDeserialize(new Movies(MoviesData.Movies));
102+
}
103+
98104
[Test]
99105
public void Can_Serialize_MovieResponse_Dto()
100106
{

0 commit comments

Comments
 (0)