Modern C#: System.Text.Json
Since .NET Core 3.1 .NET comes with the System.Text.Json
namespace which allows JSON (De-)Serialization without using any library.
From the Microsoft documentation:
The System.Text.Json
namespace provides functionality for serializing to and deserializing from JavaScript Object Notation (JSON). The System.Text.Json
library is included in the runtime for .NET Core 3.1 and later versions. For other target frameworks, install the System.Text.Json
NuGet package. The package supports:
- .NET Standard 2.0 and later versions
- .NET Framework 4.7.2 and later versions
- .NET Core 2.0, 2.1, and 2.2
To deserialize you need to use an appropriate type of your choice that can hold multiple values like e.g IEnumerable<string>
, List<string>
, IReadOnlyCollection<string>
etc. whatever is the datatype that fits your needs best.
Using C# 11 and .NET 7 you can now use raw string literals, which makes declaring JSON in code much easier and more readable and you don't need to escape every "
.
using System.Text.Json;
var content = """
[
"on4ThnU7",
"n71YZYVKD",
"CVfSpM2W",
"10kQotV"
]
""";
var serialized = JsonSerializer.Deserialize<IReadOnlyCollection<string>>(content);
foreach (var item in serialized)
{
Console.WriteLine(item);
}
Expected output:
on4ThnU7
n71YZYVKD
CVfSpM2W
10kQotV
For how to migrate from Newtonsoft.Json
to System.Text.Json
see the Microsoft documentation.