This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
This article shows how to use theSystem.Text.Json namespace to serialize to JavaScript Object Notation (JSON). If you're porting existing code fromNewtonsoft.Json, seeHow to migrate toSystem.Text.Json.
Tip
You can use AI assistance toserialize to JSON.
To write JSON to a string or to a file, call theJsonSerializer.Serialize method.
The following example creates JSON as a string:
using System.Text.Json;namespace SerializeBasic{ public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static void Main() { var weatherForecast = new WeatherForecast { Date = DateTime.Parse("2019-08-01"), TemperatureCelsius = 25, Summary = "Hot" }; string jsonString = JsonSerializer.Serialize(weatherForecast); Console.WriteLine(jsonString); } }}// output://{"Date":"2019-08-01T00:00:00-07:00","TemperatureCelsius":25,"Summary":"Hot"}Dim jsonString As StringThe JSON output isminified (whitespace, indentation, and new-line characters are removed) by default.
The following example uses synchronous code to create a JSON file:
using System.Text.Json;namespace SerializeToFile{ public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static void Main() { var weatherForecast = new WeatherForecast { Date = DateTime.Parse("2019-08-01"), TemperatureCelsius = 25, Summary = "Hot" }; string fileName = "WeatherForecast.json"; string jsonString = JsonSerializer.Serialize(weatherForecast); File.WriteAllText(fileName, jsonString); Console.WriteLine(File.ReadAllText(fileName)); } }}// output://{"Date":"2019-08-01T00:00:00-07:00","TemperatureCelsius":25,"Summary":"Hot"}jsonString = JsonSerializer.Serialize(weatherForecast1)File.WriteAllText(fileName, jsonString)The following example uses asynchronous code to create a JSON file:
using System.Text.Json;namespace SerializeToFileAsync{ public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static async Task Main() { var weatherForecast = new WeatherForecast { Date = DateTime.Parse("2019-08-01"), TemperatureCelsius = 25, Summary = "Hot" }; string fileName = "WeatherForecast.json"; await using FileStream createStream = File.Create(fileName); await JsonSerializer.SerializeAsync(createStream, weatherForecast); Console.WriteLine(File.ReadAllText(fileName)); } }}// output://{"Date":"2019-08-01T00:00:00-07:00","TemperatureCelsius":25,"Summary":"Hot"}Dim createStream As FileStream = File.Create(fileName)Await JsonSerializer.SerializeAsync(createStream, weatherForecast1)The preceding examples use type inference for the type being serialized. An overload ofSerialize() takes a generic type parameter:
using System.Text.Json;namespace SerializeWithGenericParameter{ public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static void Main() { var weatherForecast = new WeatherForecast { Date = DateTime.Parse("2019-08-01"), TemperatureCelsius = 25, Summary = "Hot" }; string jsonString = JsonSerializer.Serialize<WeatherForecast>(weatherForecast); Console.WriteLine(jsonString); } }}// output://{"Date":"2019-08-01T00:00:00-07:00","TemperatureCelsius":25,"Summary":"Hot"}jsonString = JsonSerializer.Serialize(Of WeatherForecastWithPOCOs)(weatherForecast)You can also use AI to generate serialization code for you. For instructions, see theUse AI section in this article.
When you use System.Text.Json indirectly in an ASP.NET Core app, some default behaviors are different. For more information, seeWeb defaults for JsonSerializerOptions.
Supported types include:
.NET primitives that map to JavaScript primitives, such as numeric types, strings, and Boolean.
User-definedplain old CLR objects (POCOs).
One-dimensional and jagged arrays (T[][]).
Collections and dictionaries from the following namespaces:
For more information, seeSupported types in System.Text.Json.
You canimplement custom converters to handle additional types or to provide functionality that isn't supported by the built-in converters.
Here's an example showing how a class that contains collection properties and a user-defined type is serialized:
using System.Text.Json;namespace SerializeExtra{ public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } public string? SummaryField; public IList<DateTimeOffset>? DatesAvailable { get; set; } public Dictionary<string, HighLowTemps>? TemperatureRanges { get; set; } public string[]? SummaryWords { get; set; } } public class HighLowTemps { public int High { get; set; } public int Low { get; set; } } public class Program { public static void Main() { var weatherForecast = new WeatherForecast { Date = DateTime.Parse("2019-08-01"), TemperatureCelsius = 25, Summary = "Hot", SummaryField = "Hot", DatesAvailable = new List<DateTimeOffset>() { DateTime.Parse("2019-08-01"), DateTime.Parse("2019-08-02") }, TemperatureRanges = new Dictionary<string, HighLowTemps> { ["Cold"] = new HighLowTemps { High = 20, Low = -10 }, ["Hot"] = new HighLowTemps { High = 60 , Low = 20 } }, SummaryWords = new[] { "Cool", "Windy", "Humid" } }; var options = new JsonSerializerOptions { WriteIndented = true }; string jsonString = JsonSerializer.Serialize(weatherForecast, options); Console.WriteLine(jsonString); } }}// output://{// "Date": "2019-08-01T00:00:00-07:00",// "TemperatureCelsius": 25,// "Summary": "Hot",// "DatesAvailable": [// "2019-08-01T00:00:00-07:00",// "2019-08-02T00:00:00-07:00"// ],// "TemperatureRanges": {// "Cold": {// "High": 20,// "Low": -10// },// "Hot": {// "High": 60,// "Low": 20// }// },// "SummaryWords": [// "Cool",// "Windy",// "Humid"// ]//}Public Class WeatherForecastWithPOCOs Public Property [Date] As DateTimeOffset Public Property TemperatureCelsius As Integer Public Property Summary As String Public SummaryField As String Public Property DatesAvailable As IList(Of DateTimeOffset) Public Property TemperatureRanges As Dictionary(Of String, HighLowTemps) Public Property SummaryWords As String()End ClassPublic Class HighLowTemps Public Property High As Integer Public Property Low As IntegerEnd Class' serialization output formatted (pretty-printed with whitespace and indentation):' {' "Date": "2019-08-01T00:00:00-07:00",' "TemperatureCelsius": 25,' "Summary": "Hot",' "DatesAvailable": [' "2019-08-01T00:00:00-07:00",' "2019-08-02T00:00:00-07:00"' ],' "TemperatureRanges": {' "Cold": {' "High": 20,' "Low": -10' },' "Hot": {' "High": 60,' "Low": 20' }' },' "SummaryWords": [' "Cool",' "Windy",' "Humid"' ]' }It's 5-10% faster to serialize to a UTF-8 byte array than to use the string-based methods. That's because the bytes (as UTF-8) don't need to be converted to strings (UTF-16).
To serialize to a UTF-8 byte array, call theJsonSerializer.SerializeToUtf8Bytes method:
byte[] jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(weatherForecast);Dim jsonUtf8Bytes As Byte()Dim options As JsonSerializerOptions = New JsonSerializerOptions With { .WriteIndented = True}jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(weatherForecast1, options)ASerialize overload that takes aUtf8JsonWriter is also available.
To pretty-print the JSON output, setJsonSerializerOptions.WriteIndented totrue:
using System.Text.Json;namespace SerializeWriteIndented{ public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static void Main() { var weatherForecast = new WeatherForecast { Date = DateTime.Parse("2019-08-01"), TemperatureCelsius = 25, Summary = "Hot" }; var options = new JsonSerializerOptions { WriteIndented = true }; string jsonString = JsonSerializer.Serialize(weatherForecast, options); Console.WriteLine(jsonString); } }}// output://{// "Date": "2019-08-01T00:00:00-07:00",// "TemperatureCelsius": 25,// "Summary": "Hot"//}Dim options As JsonSerializerOptions = New JsonSerializerOptions With { .WriteIndented = True}jsonString = JsonSerializer.Serialize(weatherForecast, options)Starting in .NET 9, you can also customize the indent character and size usingIndentCharacter andIndentSize.
Tip
If you useJsonSerializerOptions repeatedly with the same options, don't create a newJsonSerializerOptions instance each time you use it. Reuse the same instance for every call. For more information, seeReuse JsonSerializerOptions instances.
You can use AI tools, such as GitHub Copilot, to generate code that usesSystem.Text.Json to serialize to JSON. You can customize the prompt to fit your object fields and serialization needs.
Here's an example prompt you can use to generate serialization code:
I have a variable named weatherForecast of type WeatherForecast.Serialize the variable using System.Text.Json and write the result directly to a file named "output.json" with the JSON indented for pretty formatting.Ensure the code includes all necessary using directives and compiles without errors.Review Copilot's suggestions before applying them.
For more information about GitHub Copilot, see GitHub'sFAQs.
Was this page helpful?
Need help with this topic?
Want to try using Ask Learn to clarify or guide you through this topic?
Was this page helpful?
Want to try using Ask Learn to clarify or guide you through this topic?