本文へスキップ
BecomeCoder

C#実践コース · 第11章 モダンC#実務 · レッスン63

System.Text.Json を使いこなす

ブラウザで完結

導入

APIとやり取りするJSONは、「キー名がC#の命名規則と違う」「一部だけ取り出したい」「見やすく整形したい」といった調整が必要になります。.NET標準の System.Text.Json は、属性やオプションでこれらを細かく制御できます。

図解

flowchart LR
    J["JSON<br/>{&quot;book_title&quot;: ...}"] -->|Deserialize + 属性| O["C# オブジェクト<br/>Title プロパティ"]
    O -->|Serialize + オプション| J2["整形/命名を制御したJSON"]
    style O fill:#e8f5e9

サンプル

using System.Text.Json;
using System.Text.Json.Serialization;

// キー名が snake_case でも、属性でC#プロパティに対応づけられる
var json = """{"book_title":"C#入門","price":1980}""";
var book = JsonSerializer.Deserialize<Book>(json)!;
Console.WriteLine($"{book.Title} / {book.Price}");   // C#入門 / 1980

// 見やすく整形して書き出す
var options = new JsonSerializerOptions { WriteIndented = true };
Console.WriteLine(JsonSerializer.Serialize(book, options));

class Book
{
    [JsonPropertyName("book_title")]
    public string Title { get; set; } = "";
    public int Price { get; set; }
}
  • [JsonPropertyName("...")] でJSONのキーとC#プロパティ名の食い違いを吸収
  • JsonSerializerOptions で整形(WriteIndented)や命名規則(PropertyNamingPolicy)を制御
  • 秘密情報を出したくないプロパティは [JsonIgnore] で除外できる

やってみよう

Book[JsonIgnore] public string Secret { get; set; } を足して Serialize の結果に出ないことを確かめたり、WriteIndented を外して1行JSONになる様子を見てみましょう。

演習

using System.Text.Json;
using System.Text.Json.Serialization;

var json = """{"user_name":"Taro"}""";
var user = JsonSerializer.Deserialize<User>(json)!;
Console.WriteLine(user.Name);   // Taro

class User
{
    // TODO: JSONのキー "user_name" を Name に対応づける属性を付けてください
    ___
    public string Name { get; set; } = "";
}
  • 期待される出力: Taro
ヒント1を見る

[JsonPropertyName("user_name")] を Name プロパティの直前に付けます

ヒント2を見る

using System.Text.Json.Serialization; があるので属性名は JsonPropertyName だけで書けます

まとめ

  • System.Text.Json は属性とオプションでJSONを細かく制御できる
  • JsonPropertyName で命名差を吸収、JsonIgnore で除外、WriteIndented で整形
  • .NET標準なので追加パッケージなしで使える

次回: 実務アプリの背骨、DI・設定・オプションです(読み物)。

実際に動かしてみよう

本文のサンプルや演習のコードは、コードブロック右上の「コピー」ボタンでコピーして、下のエディタに貼り付ければそのまま実行できます。

C# — ブラウザ内で実行

ブラウザ内でC#を動かす環境を読み込みます(初回のみ数秒)。
スクロールして表示された時点でも自動で読み込まれます。