Skip to content

Commit

Permalink
Json.NET serialization and deserialization
Browse files Browse the repository at this point in the history
  • Loading branch information
petermorlion committed May 12, 2016
1 parent a02273f commit 32cf4eb
Show file tree
Hide file tree
Showing 12 changed files with 444 additions and 20 deletions.
36 changes: 36 additions & 0 deletions RedStar.Amounts.JsonNet.Tests/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RedStar.Amounts.JsonNet.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("RedStar.Amounts.JsonNet.Tests")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c707879a-6e92-4ab2-be60-2b8285cd3a89")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
98 changes: 98 additions & 0 deletions RedStar.Amounts.JsonNet.Tests/RedStar.Amounts.JsonNet.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\xunit.core.2.1.0\build\portable-net45+win8+wp8+wpa81\xunit.core.props" Condition="Exists('..\packages\xunit.core.2.1.0\build\portable-net45+win8+wp8+wpa81\xunit.core.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{ECC089C3-8167-4C25-8E9D-F76B1ED63799}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>RedStar.Amounts.JsonNet.Tests</RootNamespace>
<AssemblyName>RedStar.Amounts.JsonNet.Tests</AssemblyName>
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>97d30ad2</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="xunit.assert, Version=2.1.0.3179, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\packages\xunit.assert.2.1.0\lib\portable-net45+win8+wp8+wpa81\xunit.assert.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="xunit.core, Version=2.1.0.3179, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\packages\xunit.extensibility.core.2.1.0\lib\portable-net45+win8+wp8+wpa81\xunit.core.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="xunit.execution.desktop, Version=2.1.0.3179, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll</HintPath>
<Private>True</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="StringAmountJsonConverterTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\RedStar.Amounts.JsonNet\RedStar.Amounts.JsonNet.csproj">
<Project>{A05B6FC6-465F-408D-ADFA-4A5B14A572B2}</Project>
<Name>RedStar.Amounts.JsonNet</Name>
</ProjectReference>
<ProjectReference Include="..\RedStar.Amounts.StandardUnits\RedStar.Amounts.StandardUnits.csproj">
<Project>{B3EEAF5A-75DC-4C91-8BDB-C3E9A01B9E98}</Project>
<Name>RedStar.Amounts.StandardUnits</Name>
</ProjectReference>
<ProjectReference Include="..\RedStar.Amounts\RedStar.Amounts.csproj">
<Project>{961A7DCF-6242-41D5-A5B9-6195057C80D4}</Project>
<Name>RedStar.Amounts</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\xunit.core.2.1.0\build\portable-net45+win8+wp8+wpa81\xunit.core.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\xunit.core.2.1.0\build\portable-net45+win8+wp8+wpa81\xunit.core.props'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
134 changes: 134 additions & 0 deletions RedStar.Amounts.JsonNet.Tests/StringAmountJsonConverterTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
using System.Globalization;
using Newtonsoft.Json;
using RedStar.Amounts.StandardUnits;
using Xunit;

namespace RedStar.Amounts.JsonNet.Tests
{
public class StringAmountJsonConverterTests
{
private readonly JsonSerializerSettings _settings;

public StringAmountJsonConverterTests()
{
UnitManager.RegisterByAssembly(typeof(LengthUnits).Assembly);

_settings = new JsonSerializerSettings
{
Culture = new CultureInfo("en"),
Converters = new JsonConverter[]
{
new StringAmountJsonConverter()
}
};
}

[Fact]
public void WhenConvertingAmount_ReturnString()
{
var amount = new Amount(30, MassUnits.KiloGram);

var result = JsonConvert.SerializeObject(amount, _settings);

Assert.Equal("\"30 Kg\"", result);
}

[Fact]
public void WhenConvertingNull_ReturnNull()
{
var result = JsonConvert.SerializeObject(null, _settings);

Assert.Equal("null", result);
}

[Fact]
public void WhenConvertingJson_ReturnAmount()
{
var json = "\"3.4 Kg\"";

var result = JsonConvert.DeserializeObject<Amount>(json, _settings);

Assert.Equal(new Amount(3.4, MassUnits.KiloGram), result);
}

[Fact]
public void WhenConvertingNullJson_ReturnNull()
{
var json = "null";

var result = JsonConvert.DeserializeObject<Amount>(json, _settings);

Assert.Null(result);
}

[Fact]
public void WhenConvertingCalculatedUnit_ReturnAmount()
{
var expected = new Amount(3.4, VolumeUnits.Meter3 / TimeUnits.Hour);
var json = "\"3.4 m³/h\"";

var actual = JsonConvert.DeserializeObject<Amount>(json, _settings);

Assert.Equal(expected, actual);
}

[Fact]
public void WhenConvertingMultipleTimes_KeepValuesConsistent()
{
var amount = new Amount(0, TemperatureUnits.DegreeCelcius / TimeUnits.Second);

for (var i = 0; i < 10; i++)
{
var json = JsonConvert.SerializeObject(amount, _settings);
amount = JsonConvert.DeserializeObject<Amount>(json, _settings);

Assert.Equal("\"0 °C/s\"", json);
Assert.Equal(new Amount(0, TemperatureUnits.DegreeCelcius / TimeUnits.Second), amount);
}
}

[Fact]
public void WhenConvertingComplexCalculatedUnit_ReturnAMount()
{
var jsonString = "\"0.003 GJ/10*Kg\"";
var expectedAmount = new Amount(0.003, EnergyUnits.GigaJoule / 10 * MassUnits.KiloGram);

var actualAmount = JsonConvert.DeserializeObject<Amount>(jsonString, _settings);
Assert.Equal(expectedAmount, actualAmount);
}

[Fact]
public void WhenConvertingComplexCalculatedUnit_ReturnJson()
{
var expectedJsonString = "\"0.003 GJ/10*Kg\"";
var amount = new Amount(0.003, EnergyUnits.GigaJoule / 10 * MassUnits.KiloGram);

var actualJsonString = JsonConvert.SerializeObject(amount, _settings);
Assert.Equal(expectedJsonString, actualJsonString);
}

[Fact]
public void WhenConvertingNullProperty_ReturnJson()
{
var obj = new MyClass();
var expectedJsonString = "{\"MyProperty\":null}";

var actualJsonString = JsonConvert.SerializeObject(obj, _settings);
Assert.Equal(expectedJsonString, actualJsonString);
}

[Fact]
public void WhenConvertingNullJson_ReturnObjectWithNullProperty()
{
var jsonString = "{\"MyProperty\":null}";

var newObj = JsonConvert.DeserializeObject<MyClass>(jsonString, _settings);
Assert.Null(newObj.MyProperty);
}

private class MyClass
{
public Amount MyProperty { get; set; }
}
}
}
10 changes: 10 additions & 0 deletions RedStar.Amounts.JsonNet.Tests/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="8.0.3" targetFramework="net451" />
<package id="xunit" version="2.1.0" targetFramework="net451" />
<package id="xunit.abstractions" version="2.0.0" targetFramework="net451" />
<package id="xunit.assert" version="2.1.0" targetFramework="net451" />
<package id="xunit.core" version="2.1.0" targetFramework="net451" />
<package id="xunit.extensibility.core" version="2.1.0" targetFramework="net451" />
<package id="xunit.extensibility.execution" version="2.1.0" targetFramework="net451" />
</packages>
36 changes: 36 additions & 0 deletions RedStar.Amounts.JsonNet/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RedStar.Amounts.JsonNet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("RedStar.Amounts.JsonNet")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c62c3ce1-36b4-419f-ac35-8a4553ced732")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
66 changes: 66 additions & 0 deletions RedStar.Amounts.JsonNet/RedStar.Amounts.JsonNet.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{A05B6FC6-465F-408D-ADFA-4A5B14A572B2}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>RedStar.Amounts.JsonNet</RootNamespace>
<AssemblyName>RedStar.Amounts.JsonNet</AssemblyName>
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="StringAmountJsonConverter.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\RedStar.Amounts\RedStar.Amounts.csproj">
<Project>{961A7DCF-6242-41D5-A5B9-6195057C80D4}</Project>
<Name>RedStar.Amounts</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
Loading

0 comments on commit 32cf4eb

Please sign in to comment.