I accidentally introduced a breaking change in my API by switching to System.Text.Json
in my ASP.NET Core app. I had a client that was sending a JSON document and was using numbers 1
or 0
for boolean fields instead of true
or false
:
// What they're sending.
{ "Active": 1 }
// What they should be sending.
{ "Active": true }
The Newtonsoft.Json
library automatically handled this by casting numbers to bools (0 = false
, everything else = true
), but System.Text.Json
doesn't do this; it throws an exception instead. This means my API endpoints suddenly stopped working for my silly client who's sending 1
's and 0
's!
I can't seem to find any mention of this in the migration guide. I would like to restore the behavior back to how Newtonsoft handles it, but I'm not sure if there's a flag to enable it somewhere I'm not seeing, or whether I'll have to write a custom converter.
Could someone help me restore the behavior to be like Newtonsoft's?
Here's some code to demonstrate the issue:
using System;
string data = "{ \"Active\": 1 }";
try
{
OutputState s1 = System.Text.Json.JsonSerializer.Deserialize<OutputState>(data);
Console.WriteLine($"OutputState 1: {s1.Active}");
}
catch (Exception ex)
{
Console.WriteLine($"System.Text.Json failed: {ex.Message}");
}
try
{
OutputState s2 = Newtonsoft.Json.JsonConvert.DeserializeObject<OutputState>(data);
Console.WriteLine($"OutputState 2: {s2.Active}");
}
catch (Exception ex)
{
Console.WriteLine($"Newtonsoft.Json failed: {ex.Message}");
}
public record OutputState(bool Active);
Also a .NET fiddle for an interactive playground: https://dotnetfiddle.net/xgm2u7
System.Text.Json
:System.Text.Json failed: Deserialization of reference types without parameterless constructor is not supported. Type 'OutputState'
(though it works with a class). – Cannes