Trying to convert an old ASP.NET Core project from Newtonsoft.Json to System.Text.Json but it changes the behavior of nullable reference type conversion. System.Text.Json serializes/deserialize nullable reference types to "{}" as opposed to "null". How do I fix it? I want to get rid of Newtonsoft.Json.
services.AddMvc().AddNewtonsoftJson();
Here is the type for that List public IList<IDictionary<string, object>> List { get; set; }
. The actual value type is DBNull
.
System.Text.Json
{
"data": {
"list": [
{
"headers": [],
"list": [
{
"id": "3faab29e-982d-ccb9-197b-08db24ef09e7",
"contractType": "Basis",
"tEvent": "Edit",
"Basis": 0.0000,
"fees": {},
"FlatPrice": {},
"theirContract": {}
},
Newtonsoft.Json
{
"data": {
"list": [
{
"headers": [],
"list": [
{
"id": "3faab29e-982d-ccb9-197b-08db24ef09e7",
"contractType": "Basis",
"tEvent": "Edit",
"Basis": 0.0000,
"fees": null,
"FlatPrice": null,
"theirContract": null
},
2
Answers
As stated here there is not built-in support for DBNull.
You have to use a custom converter:
Then add it to the options:
As at the time of writing,
System.Text.Json
does not have built-in support forDBNull
.Instead, you can write a custom
JsonConverter
to handleDBNull
values, by overriding the converter’sWrite()
method to print out the JSON literalnull
instead:Then, pass this converter to the
JsonSerializerOptions
of yourJsonSerializer
: