導入
APIが返す{"name":"Taro","age":20}はただの文字列です。これをC#のオブジェクトに変換して、.Nameのように扱えるようにするのがデシリアライズ。System.Text.Jsonが担います。
図解
flowchart LR
J["JSON文字列<br/>{"name":"Taro","age":20}"] -->|Deserialize<User>| O["User オブジェクト<br/>Name=Taro, Age=20"]
style O fill:#e8f5e9
サンプル
string json = """
{ "name": "Taro", "age": 20 }
""";
// JSON文字列 → C#オブジェクト
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
User user = JsonSerializer.Deserialize<User>(json, options)!;
Console.WriteLine($"{user.Name}({user.Age}歳)"); // Taro(20歳)
record User(string Name, int Age);
JsonSerializer.Deserialize<型>(json)でJSON文字列をオブジェクトに変換- 受け皿は
recordが最適(データの入れ物) PropertyNameCaseInsensitiveで"name"とNameの大文字小文字差を吸収
演習
string json = """
[ { "name": "コーヒー", "price": 500 }, { "name": "ケーキ", "price": 400 } ]
""";
// TODO: List<Item> にデシリアライズし、price の合計を "合計: 900円" と出力してください
// (Item は name, price を持つ record)
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
___
- 期待される出力:
合計: 900円
ヒント1を見る
JsonSerializer.Deserialize<List<Item>>(json, options) の後 LINQ のSum
ヒント2を見る
var items = JsonSerializer.Deserialize<List<Item>>(json, options)!; Console.WriteLine($"合計: {items.Sum(i => i.Price)}円"); record Item(string Name, int Price);
まとめ
JsonSerializer.Deserialize<型>でJSON→オブジェクト- 受け皿は
recordが便利 - 大文字小文字差はオプションで吸収
次回: 逆にオブジェクトをJSONにする「シリアライズ」です。