~euantorano/system.text.json-object-serialization

361368ff9bdcb75072c0895dfcdbc2317bf3c744 — Euan Torano 1 year, 3 months ago
Initial commit
A  => .builds/debian-buster.yml +8 -0
@@ 1,8 @@
image: debian/buster
packages:
- dotnet-sdk-3.1
repositories:
  microsoft.prod: https://packages.microsoft.com/debian/10/prod buster main EB3E94ADBE1229CF
tasks:
- test: |
    dotnet test

A  => .gitignore +4 -0
@@ 1,4 @@
bin/
obj/
/packages/
.idea

A  => JsonEncodeTest.sln +16 -0
@@ 1,16 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JsonEncodeTest", "JsonEncodeTest\JsonEncodeTest.csproj", "{B3DE5DDA-14B5-4B67-BE20-09E8FD49BE26}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{B3DE5DDA-14B5-4B67-BE20-09E8FD49BE26}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{B3DE5DDA-14B5-4B67-BE20-09E8FD49BE26}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{B3DE5DDA-14B5-4B67-BE20-09E8FD49BE26}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{B3DE5DDA-14B5-4B67-BE20-09E8FD49BE26}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
EndGlobal

A  => JsonEncodeTest/BaseClass.cs +35 -0
@@ 1,35 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace JsonEncodeTest
{
    public class BaseClass
    {
        [JsonPropertyName("int_val")]
        [JsonProperty("int_val")]
        public int IntVal { get; set; }

        public string ToJsonSystemText()
        {
            return JsonSerializer.Serialize(this, GetType(), new JsonSerializerOptions()
            {
                WriteIndented = false
            });
        }

        public string ToJsonSystemTextBroken()
        {
            return JsonSerializer.Serialize(this, new JsonSerializerOptions()
            {
                WriteIndented = false
            });
        }

        public string ToJsonJsonNet()
        {
            return JsonConvert.SerializeObject(this, Formatting.None);
        }
    }
}
\ No newline at end of file

A  => JsonEncodeTest/JsonEncodeTest.csproj +18 -0
@@ 1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <TargetFramework>netcoreapp3.1</TargetFramework>

        <IsPackable>false</IsPackable>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
        <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
        <PackageReference Include="System.Text.Json" Version="4.7.1" />
        <PackageReference Include="xunit" Version="2.4.0" />
        <PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
        <PackageReference Include="coverlet.collector" Version="1.0.1" />
    </ItemGroup>

</Project>

A  => JsonEncodeTest/SerializeTests.cs +58 -0
@@ 1,58 @@
using Xunit;

namespace JsonEncodeTest
{
    public class SerializeTests
    {
        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public void TestBaseClassToJson(bool useNewtonSoft)
        {
            const string expected = "{\"int_val\":42}";

            var bc = new BaseClass
            {
                IntVal = 42
            };

            var actual = useNewtonSoft ? bc.ToJsonJsonNet() : bc.ToJsonSystemText();

            Assert.Equal(expected, actual);
        }

        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public void TestSubClassToJson(bool useNewtonSoft)
        {
            const string expected = "{\"string_val\":\"hello world\",\"int_val\":42}";

            var sc = new SubClass
            {
                StringVal = "hello world",
                IntVal = 42
            };

            var actual = useNewtonSoft ? sc.ToJsonJsonNet() : sc.ToJsonSystemText();

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestBrokenSubClassToJson()
        {
            const string expected = "{\"int_val\":42}";

            var sc = new SubClass
            {
                StringVal = "hello world",
                IntVal = 42
            };

            var actual = sc.ToJsonSystemTextBroken();

            Assert.Equal(expected, actual);
        }
    }
}
\ No newline at end of file

A  => JsonEncodeTest/SubClass.cs +12 -0
@@ 1,12 @@
using System.Text.Json.Serialization;
using Newtonsoft.Json;

namespace JsonEncodeTest
{
    public class SubClass : BaseClass
    {
        [JsonProperty("string_val")]
        [JsonPropertyName("string_val")]
        public string StringVal { get; set; }
    }
}
\ No newline at end of file

A  => LICENSE +8 -0
@@ 1,8 @@
Copyright (c) 2020 Euan Torano. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

A  => README.md +5 -0
@@ 1,5 @@
# `System.Text.Json` Object Serialization ![https://git.sr.ht/~euantorano/system.text.json-object-serialization](https://builds.sr.ht/~euantorano/system.text.json-object-serializationsvg)

This is a companion repository for my post [`C# JSON encoding with System.Text.Json - a small gotcha`](https://www.euantorano.co.uk/posts/system.text.json-object-serialization/).

It shows the approach you would expect to work, and the approach that atually works.