Handling .NET Nullable Types in System.Text.Json

Ambar Prajapati
2 min readAug 29, 2020

How to handle .NET Nullable Types during Json Serialization in System.Text.Json — (C# Example for Nullable long type)

If a C#struct or class carries nullable serializable member like below

public long? STUDENT_ID { get; set; }

and if appropriate conersion is not applied for Json serialization, then we will see run-time error like below —

The JSON value could not be converted to System.Nullable.

Unfortunately, there is no direct way to handle the Nullable types in System.Text.Json unless you are ready to go little further and customize the read and write during serialization.

With version 5 of System.Text.Json, which is still under preview as of this date —

using System.Text.Json.Serialization

we can write a Custom Converter like below

This can be added via options —

And then the De-serialization statement can handle Nullable types.

The custom converter will yield the deserialized values —
0 for incoming nulls,
Int64 values for actual long values and
nulls if the matching Json property is not found.

That’s it.
Goodluck with .NET Nullable types and Microsoft Json Serialization!

--

--