導入
HTTP通信の回でSystem.Text.Jsonの基本に触れました。実務ではもう一歩踏み込んだ制御——「JSONのキー名とC#のプロパティ名の食い違い」「秘密情報を出さない」——が必要です。属性による制御を押さえます。
図解
flowchart LR
API["APIのJSON<br/>user_name(スネークケース)"] -->|JsonPropertyName で対応付け| CS["C♯プロパティ<br/>UserName(パスカルケース)"]
サンプル
using System.Text.Json.Serialization;
string json = """
{ "user_name": "Taro", "created_at": "2026-07-10" }
""";
// APIはスネークケース、C#はパスカルケース。JsonPropertyName で橋渡し
var user = JsonSerializer.Deserialize<User>(json)!;
Console.WriteLine($"{user.UserName}(登録: {user.CreatedAt})");
// Taro(登録: 2026-07-10)
record User(
[property: JsonPropertyName("user_name")] string UserName,
[property: JsonPropertyName("created_at")] string CreatedAt);
[JsonPropertyName("キー名")]でJSONキーとC#プロパティ名の食い違いを吸収[JsonIgnore]を付けたプロパティは出力されない(パスワードなど秘密情報の保護に必須)- 標準は
System.Text.Json。既存プロジェクトでは老舗のNewtonsoft.Jsonにも出会う(読めるように)
演習
using System.Text.Json.Serialization;
string json = """
{ "item_name": "モニター", "unit_price": 19800 }
""";
// TODO: JsonPropertyName で item_name/unit_price を対応付けた Item record を定義し、
// "モニター: 19800円" と出力してください
___
- 期待される出力:
モニター: 19800円
ヒント1を見る
record Item([property: JsonPropertyName("item_name")] string ItemName, [property: JsonPropertyName("unit_price")] int UnitPrice);
ヒント2を見る
var item = JsonSerializer.Deserialize<Item>(json)!; Console.WriteLine($"{item.ItemName}: {item.UnitPrice}円");
まとめ
[JsonPropertyName]でキー名の食い違いを吸収[JsonIgnore]で秘密情報を出さない- 新規は
System.Text.Json、既存はNewtonsoft.Jsonも読めるように
次回: DBの生の接続操作ADO.NETです。