Introduction
I have been coding in C# and we have been given the premise to remove all third-party libraries to avoid tightly-coupling our code with third-party libraries. However, I often find Microsoft’s .NET code to be buggy. (I have had more than one library with bugs in the Microsoft .NET library).
Issue
We need to serialize objects to strings of JSON. Normally I would use the robust and reliable Newtonsoft library, but as mentioned above, I began doing this using System.Text.Json.JsonSerializer.Serialize(object) instead of the Newtonsoft.Json.JsonConvert.SerializeObject(object) to get this JSON string text.
However, I will often get an empty string using the System.Text.Json library. Why is this?
Theory
I have read on other posts about fields not being serialized correctly in System.Text.Json library. I suspect that it is the Intermediary Language (IL) that is being serialized, and if you use a tool like ILDASM to inspect the IL you will see that auto-properties are serialized into properties with backing-fields. Is it more of the same issue mentioned in posts like this one but presenting differently?
Summary (TL;DR)
I’ve written a proof-of-concept to show this issue. Why does only one test pass in the following code?
public class MySerializeTest
{
private static readonly TestLogin myLogin = new()
{
UserName = "[email protected]",
Password = "Pass123"
};
[Test]
public void TestSystem()
{
var serialisedJsonText = Parser.ParseSystem(myLogin);
Assert.That(serialisedJsonText.Length, Is.GreaterThan(3), "Using SYSTEM - the length should be more than this.");
}
[Test]
public void TestLegacy()
{
var serialisedJsonText = Parser.ParseNewton(myLogin);
Assert.That(serialisedJsonText.Length, Is.GreaterThan(3), "Using NEWTONSOFT - length should be more than this.");
}
}
public interface ITest;
public class TestLogin : ITest
{
[System.Text.Json.Serialization.JsonPropertyName("userName")]
[Newtonsoft.Json.JsonProperty("userName")]
public string? UserName { get; set; }
[System.Text.Json.Serialization.JsonPropertyName("password")]
[Newtonsoft.Json.JsonProperty("password")]
public string? Password { get; set; }
}
public class Parser
{
public static string ParseSystem(ITest request)
{
return System.Text.Json.JsonSerializer.Serialize(request);
}
public static string ParseNewton(ITest request)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(request);
}
}