導入
APIとやり取りするJSONは、「キー名がC#の命名規則と違う」「一部だけ取り出したい」「見やすく整形したい」といった調整が必要になります。.NET標準の System.Text.Json は、属性やオプションでこれらを細かく制御できます。
図解
flowchart LR
J["JSON<br/>{"book_title": ...}"] -->|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・設定・オプションです(読み物)。