File tree 3 files changed +46
-9
lines changed
3 files changed +46
-9
lines changed Original file line number Diff line number Diff line change 1
1
using System ;
2
+ using System . Reflection ;
2
3
3
4
namespace JsonApiDotNetCore . Internal
4
5
{
5
6
public static class TypeHelper
6
7
{
7
8
public static object ConvertType ( object value , Type type )
8
9
{
9
- if ( value == null )
10
- return null ;
10
+ try
11
+ {
12
+ if ( value == null )
13
+ return null ;
14
+
15
+ type = Nullable . GetUnderlyingType ( type ) ?? type ;
16
+
17
+ var stringValue = value . ToString ( ) ;
11
18
12
- type = Nullable . GetUnderlyingType ( type ) ?? type ;
19
+ if ( type == typeof ( Guid ) )
20
+ return Guid . Parse ( stringValue ) ;
13
21
14
- var stringValue = value . ToString ( ) ;
15
-
16
- if ( type == typeof ( Guid ) )
17
- return Guid . Parse ( stringValue ) ;
22
+ if ( type == typeof ( DateTimeOffset ) )
23
+ return DateTimeOffset . Parse ( stringValue ) ;
18
24
19
- return Convert . ChangeType ( stringValue , type ) ;
25
+ return Convert . ChangeType ( stringValue , type ) ;
26
+ }
27
+ catch ( Exception )
28
+ {
29
+ if ( type . GetTypeInfo ( ) . IsValueType )
30
+ return Activator . CreateInstance ( type ) ;
31
+
32
+ return null ;
33
+ }
20
34
}
21
35
}
22
36
}
Original file line number Diff line number Diff line change 1
1
<Project Sdk =" Microsoft.NET.Sdk" >
2
2
<PropertyGroup >
3
- <VersionPrefix >2.0.7 </VersionPrefix >
3
+ <VersionPrefix >2.0.8 </VersionPrefix >
4
4
<TargetFrameworks >netstandard1.6</TargetFrameworks >
5
5
<AssemblyName >JsonApiDotNetCore</AssemblyName >
6
6
<PackageId >JsonApiDotNetCore</PackageId >
Original file line number Diff line number Diff line change
1
+ using System ;
2
+ using JsonApiDotNetCore . Internal ;
3
+ using Xunit ;
4
+
5
+ namespace UnitTests . Internal
6
+ {
7
+ public class TypeHelper_Tests
8
+ {
9
+ [ Fact ]
10
+ public void Can_Convert_DateTimeOffsets ( )
11
+ {
12
+ // arrange
13
+ var dto = DateTimeOffset . Now ;
14
+ var formattedString = dto . ToString ( "O" ) ;
15
+
16
+ // act
17
+ var result = TypeHelper . ConvertType ( formattedString , typeof ( DateTimeOffset ) ) ;
18
+
19
+ // assert
20
+ Assert . Equal ( dto , result ) ;
21
+ }
22
+ }
23
+ }
You can’t perform that action at this time.
0 commit comments