次の方法で共有


.NET オブジェクトを JSON として書き込む方法 (シリアル化)

この記事では、 System.Text.Json 名前空間を使用して JavaScript Object Notation (JSON) にシリアル化する方法について示します。 Newtonsoft.Jsonから既存のコードを移植する場合は、 System.Text.Jsonに移行する方法」を参照してください

ヒント

AI アシスタンスを使用して、 GitHub Copilot で JSON にシリアル化できます。

JSON を文字列またはファイルに書き込むには、 JsonSerializer.Serialize メソッドを呼び出します。

シリアル化の例

次の例では、JSON を文字列として作成します。

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

既定では、JSON 出力は縮小されます (空白、インデント、および改行文字が削除されます)。

次の例では、同期コードを使用して JSON ファイルを作成します。

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)

次の例では、非同期コードを使用して JSON ファイルを作成します。

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)

前の例では、シリアル化する型に型の推定を使用しています。 Serialize() のオーバーロードでは、ジェネリック型パラメーターを受け取ります。

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)

GitHub Copilot を使用してシリアル化コードを生成することもできます。 手順については、この記事の GitHub Copilot の使用 セクションを参照してください。

シリアル化の動作

ASP.NET Core アプリで System.Text.Json を間接的に使用する場合、一部の既定の動作が異なります。 詳細については、「JsonSerializerOptions の Web の規定値」を参照してください。

サポートされる型には次のようなものがあります。

カスタム コンバーターを実装 して、追加の型を処理したり、組み込みコンバーターではサポートされていない機能を提供したりすることができます。

コレクションのプロパティとユーザー定義型が含まれるクラスをシリアル化する方法の例を次に示します。

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 Class

Public Class HighLowTemps
    Public Property High As Integer
    Public Property Low As Integer
End 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"
'   ]
' }

UTF-8 にシリアル化する

文字列ベースのメソッドを使用するよりも、UTF-8 バイトの配列にシリアル化するほうが 5% から 10% 速くなります。 バイト (UTF-8) を文字列 (UTF-16) に変換する必要がないからです。

UTF-8 バイト配列にシリアル化するには、 JsonSerializer.SerializeToUtf8Bytes メソッドを呼び出します。

byte[] jsonUtf8Bytes =JsonSerializer.SerializeToUtf8Bytes(weatherForecast);
Dim jsonUtf8Bytes As Byte()
Dim options As JsonSerializerOptions = New JsonSerializerOptions With {
    .WriteIndented = True
}
jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(weatherForecast1, options)

Utf8JsonWriter を受け取る Serialize オーバーロードも使用できます。

書式設定された JSON へのシリアル化

JSON 出力を整形するには、 JsonSerializerOptions.WriteIndentedtrueに設定します。

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)

ヒント

同じオプションで JsonSerializerOptions を繰り返し使用する場合、使用のたびに新しい JsonSerializerOptions インスタンスを作成しないでください。 すべての呼び出しで同じインスタンスを再利用します。 詳細については、 JsonSerializerOptions インスタンスの再利用に関する説明を参照してください。

GitHub Copilotを使用してJSONにシリアル化する

IDE で GitHub Copilot を使用して、System.Text.Json を使用して JSON にシリアル化するコードを生成できます。

Visual Studio 2022 バージョン 17.8 以降を使用している場合は、AI 駆動型の Visual Studio の GitHub Copilot を試して、 System.Text.Json を使用して JSON にシリアル化するコードを生成できます。 次の例のように、Copilot チャット ウィンドウにプロンプ​​トとして質問を送信します。 エディター ウィンドウ自体で インライン チャット を使用してプロンプトを送信することもできます。

Note

GitHub Copilot では AI を利用しているため、想定外のことや間違いが起こる可能性があります。 生成されたコードまたは提案を必ず確認してください。 GitHub Copilot の一般的な用途、製品への影響、人間の監視、プライバシーの詳細については、 GitHub Copilot に関する FAQを参照してください。

次のテキストは、Copilot Chat のプロンプトの例を示しています。

System.Text.Json を使用してオブジェクトを JSON 文字列にシリアル化するコードを生成します。 オブジェクトには、FirstName (文字列)、Lastname (文字列)、Age (整数) のフィールドが含まれます。 出力例を示します。

要件に合ったオブジェクト フィールドを使用するようにプロンプ​​トをカスタマイズできます。

スラッシュ コマンド、ファイル、メソッド、クラスへの参照、スレッドなどのチャット機能を使用して、意図を設定し、スコープ指定されたコンテキストでより適切な回答を得ることができます。 IDE で開いているプロジェクト内の既存のクラスの場合は、GitHub Copilot に /generate code to serialize #Classname in #Filename to JSONとプロンプトを出すことができます。

次の出力は、Copilot Chat の応答の例を示しています。

Sure! Below is an example of how to use System.Text.Json to serialize an object with the specified fields to a JSON string in C#:

using System;
using System.Text.Json;

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

public class Program
{
    public static void Main()
    {
        var person = new Person
        {
            FirstName = "John",
            LastName = "Doe",
            Age = 30
        };

        string jsonString = JsonSerializer.Serialize(person);
        Console.WriteLine(jsonString);
    }
}

**Example Output**
{"FirstName":"John","LastName":"Doe","Age":30}

This code defines a `Person` class, creates an instance of it, and then serializes it to a JSON string using `JsonSerializer.Serialize`. The resulting JSON string is then printed to the console.

Copilot がコード ブロックを返す場合、応答には、コードをコピーする、コードを新しいファイルに挿入する、またはコード出力をプレビューするオプションが含まれます。

Note

結果は、サンプルの回答に示されているものと異なる場合があります。 AI モデルは非決定論的です。つまり、同じ質問を受けたときに異なる応答を返す場合があります。 これは、時間の経過に伴う学習と適応の進行、言語バリエーション、チャット履歴などのコンテキストの変更などが原因である可能性があります。

Visual Studio で GitHub Copilot Chat を使用してオブジェクトを JSON 文字列にシリアル化する様子を示すアニメーション スクリーンショット。

詳細については、以下を参照してください: