昨天我們學了如何用 HttpClient
呼叫 Web API。
通常 API 回傳的資料會是 JSON 格式,我們今天就要學:
System.Text.Json
解析StockProfile
JSON(JavaScript Object Notation)是一種輕量化的資料交換格式。
它的結構很像 C# 的物件:
{}
包起來,包含 key-value 配對[]
包起來,存放多筆資料範例:
{
"Code": "2330",
"Name": "台積電",
"Industry": "半導體",
"Market": "TSE"
}
多筆股票資料則會是:
[
{ "Code": "2330", "Name": "台積電", "Industry": "半導體" },
{ "Code": "2303", "Name": "聯電", "Industry": "半導體" }
]
在 .NET 內建就有 System.Text.Json
命名空間,可以做 序列化 (Serialize) 和 反序列化 (Deserialize)。
using System.Text.Json;
var stock = new { Code = "2330", Name = "台積電" };
string json = JsonSerializer.Serialize(stock);
Console.WriteLine(json);
// {"Code":"2330","Name":"台積電"}
using System.Text.Json;
string json = @"{""Code"":""2330"",""Name"":""台積電""}";
var stock = JsonSerializer.Deserialize<StockProfile>(json);
Console.WriteLine($"{stock.Code} - {stock.Name}");
NuGet 是 .NET 的套件管理工具,可以快速下載與安裝外部程式庫。
在 Visual Studio:右鍵專案 → Manage NuGet Packages
在 CLI:
dotnet add package System.Text.Json
(雖然 System.Text.Json
已經內建,但有些專案可能需要更新版本)
NuGet 讓我們不需要自己造輪子,直接用別人已經寫好的功能。
StockProfile
假設我們呼叫了一個 API,回傳內容如下:
[
{ "Code": "2330", "Name": "台積電", "Industry": "半導體" },
{ "Code": "2881", "Name": "富邦金", "Industry": "金融" }
]
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using TwStockMaster.Utils.Models; // 這裡放 StockProfile 的命名空間
class Program
{
static async Task Main(string[] args)
{
HttpClient client = new HttpClient();
// 假設 API URL
string url = "https://example.com/api/stocks";
string json = await client.GetStringAsync(url);
// 反序列化成 List<StockProfile>
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true // 忽略大小寫
};
List<StockProfile>? stocks = JsonSerializer.Deserialize<List<StockProfile>>(json, options);
foreach (var stock in stocks)
{
Console.WriteLine($"{stock.Code} - {stock.Name} ({stock.Industry})");
}
}
}
今天我們學會了:
{}
與陣列 []
System.Text.Json
的序列化與反序列化StockProfile