Skip to content

add support for deserializing datetimeoffset format #119

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 2 commits into from
May 31, 2017
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
30 changes: 22 additions & 8 deletions src/JsonApiDotNetCore/Internal/TypeHelper.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,36 @@
using System;
using System.Reflection;

namespace JsonApiDotNetCore.Internal
{
public static class TypeHelper
{
public static object ConvertType(object value, Type type)
{
if(value == null)
return null;
try
{
if (value == null)
return null;

type = Nullable.GetUnderlyingType(type) ?? type;

var stringValue = value.ToString();

type = Nullable.GetUnderlyingType(type) ?? type;
if (type == typeof(Guid))
return Guid.Parse(stringValue);

var stringValue = value.ToString();

if(type == typeof(Guid))
return Guid.Parse(stringValue);
if (type == typeof(DateTimeOffset))
return DateTimeOffset.Parse(stringValue);

return Convert.ChangeType(stringValue, type);
return Convert.ChangeType(stringValue, type);
}
catch (Exception)
{
if (type.GetTypeInfo().IsValueType)
return Activator.CreateInstance(type);

return null;
}
}
}
}
2 changes: 1 addition & 1 deletion src/JsonApiDotNetCore/JsonApiDotNetCore.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<VersionPrefix>2.0.7</VersionPrefix>
<VersionPrefix>2.0.8</VersionPrefix>
<TargetFrameworks>netstandard1.6</TargetFrameworks>
<AssemblyName>JsonApiDotNetCore</AssemblyName>
<PackageId>JsonApiDotNetCore</PackageId>
Expand Down
23 changes: 23 additions & 0 deletions test/UnitTests/Internal/TypeHelper_Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using JsonApiDotNetCore.Internal;
using Xunit;

namespace UnitTests.Internal
{
public class TypeHelper_Tests
{
[Fact]
public void Can_Convert_DateTimeOffsets()
{
// arrange
var dto = DateTimeOffset.Now;
var formattedString = dto.ToString("O");

// act
var result = TypeHelper.ConvertType(formattedString, typeof(DateTimeOffset));

// assert
Assert.Equal(dto, result);
}
}
}