Skip to content

Commit ee0025f

Browse files
committed
feat(#139): handle empty strings in type helper
1 parent c08fbe0 commit ee0025f

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/JsonApiDotNetCore/Internal/TypeHelper.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ public static object ConvertType(object value, Type type)
2121

2222
var stringValue = value.ToString();
2323

24+
if (string.IsNullOrEmpty(stringValue))
25+
return GetDefaultType(type);
26+
2427
if (type == typeof(Guid))
2528
return Guid.Parse(stringValue);
2629

@@ -38,6 +41,15 @@ public static object ConvertType(object value, Type type)
3841
}
3942
}
4043

44+
private static object GetDefaultType(Type type)
45+
{
46+
if (type.GetTypeInfo().IsValueType)
47+
{
48+
return Activator.CreateInstance(type);
49+
}
50+
return null;
51+
}
52+
4153
public static T ConvertType<T>(object value)
4254
{
4355
return (T)ConvertType(value, typeof(T));

test/UnitTests/Internal/TypeHelper_Tests.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Collections.Generic;
23
using JsonApiDotNetCore.Internal;
34
using Xunit;
45

@@ -83,6 +84,29 @@ public void ConvertType_Returns_Value_If_Type_Is_Assignable()
8384
Assert.Equal(val, iResult);
8485
}
8586

87+
[Fact]
88+
public void ConvertType_Returns_Default_Value_For_Empty_Strings()
89+
{
90+
// arrange -- can't use non-constants in [Theory]
91+
var data = new Dictionary<Type, object>
92+
{
93+
{ typeof(int), 0 },
94+
{ typeof(short), (short)0 },
95+
{ typeof(long), (long)0 },
96+
{ typeof(string), "" },
97+
{ typeof(Guid), Guid.Empty },
98+
};
99+
100+
foreach (var t in data)
101+
{
102+
// act
103+
var result = TypeHelper.ConvertType(string.Empty, t.Key);
104+
105+
// assert
106+
Assert.Equal(t.Value, result);
107+
}
108+
}
109+
86110
private enum TestEnum
87111
{
88112
Test = 1

0 commit comments

Comments
 (0)