Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit editor mode

How to write .NET objects as JSON (serialize)

Feedback

In this article

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.

Serialization examples

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 String

The 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.

Serialization behavior

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:

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"'   ]' }

Serialize to UTF-8

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.

Serialize to formatted JSON

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.

Use AI to serialize to JSON

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.

See also

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNoNo

Need help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?

  • Last updated on

In this article

Was this page helpful?

YesNo
NoNeed help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?