Skip to content

Commit f33ec0b

Browse files
authored
Merge pull request #119 from Research-Institute/fix/#118
add support for deserializing datetimeoffset format
2 parents 5919517 + 2401baf commit f33ec0b

File tree

3 files changed

+46
-9
lines changed

3 files changed

+46
-9
lines changed
Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,36 @@
11
using System;
2+
using System.Reflection;
23

34
namespace JsonApiDotNetCore.Internal
45
{
56
public static class TypeHelper
67
{
78
public static object ConvertType(object value, Type type)
89
{
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();
1118

12-
type = Nullable.GetUnderlyingType(type) ?? type;
19+
if (type == typeof(Guid))
20+
return Guid.Parse(stringValue);
1321

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);
1824

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+
}
2034
}
2135
}
2236
}

src/JsonApiDotNetCore/JsonApiDotNetCore.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22
<PropertyGroup>
3-
<VersionPrefix>2.0.7</VersionPrefix>
3+
<VersionPrefix>2.0.8</VersionPrefix>
44
<TargetFrameworks>netstandard1.6</TargetFrameworks>
55
<AssemblyName>JsonApiDotNetCore</AssemblyName>
66
<PackageId>JsonApiDotNetCore</PackageId>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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+
}

0 commit comments

Comments
 (0)