在這個快速入門中,你會將熱門的 Newtonsoft.Json NuGet 套件安裝到一個.NET專案中。 NuGet 套件包含已編譯的二進位程式代碼,開發人員可讓其他開發人員在其專案中使用。 欲了解更多資訊,請參閱 《NuGet導論》。
安裝套件時,使用 dotnet package add 指令,這是 dotnet 命令列介面(CLI)的一部分。
小提示
流覽 nuget.org/packages 尋找可在您自己的應用程式中重複使用的套件。 你可以直接在 https://nuget.org/packages 搜尋,或者直接在 Visual Studio 裡找到並安裝套件。 如需詳細資訊,請參閱 尋找和評估專案的 NuGet 套件。
先決條件
提供 dotnet CLI 的 .NET SDK。 在 Visual Studio 中,dotnet CLI 會自動安裝任何與 .NET 相關的工作負載。
建立專案
你可以把 NuGet 套件安裝到 .NET 專案中。 在此快速入門中,請依照以下步驟使用 dotnet CLI 建立一個基本的 .NET 主控台專案:
為專案建立名為 Nuget.Quickstart 的資料夾。
打開命令提示字元視窗,進入新資料夾。
使用下列命令建立專案:
dotnet new console用來
dotnet run測試應用程式。 指令會將以下輸出寫入螢幕Hello, World!:
新增 Newtonsoft.Json NuGet 套件
使用下列命令來安裝
Newtonsoft.Json套件:dotnet package add Newtonsoft.Json如果你使用的是 .NET 9 或更早版本,請改用動詞優先的形式:
dotnet add package Newtonsoft.Json指令結束後,請在Visual Studio或文字編輯器中開啟 Nuget.Quickstart.csproj 檔案。 請檢查新增的 NuGet 套件參考:
<ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.4" /> </ItemGroup>
在應用程式中使用 Newtonsoft.Json API
在程式碼中,你會用 using <namespace> 指令來指代已安裝的套件,其中 <namespace> 通常是套件名稱。 接著,您可以在專案中使用套件的 API。
在Visual Studio或文字編輯器中,開啟 Program.cs 檔案。 在檔案頂端加上以下行:
using Newtonsoft.Json;新增下列程式代碼以取代
Console.WriteLine("Hello, World!");語句:namespace Nuget.Quickstart { public class Account { public string? Id { get; set; } public decimal Balance { get; set; } public DateTime Created { get; set; } } internal class Program { static void Main(string[] args) { Account account = new Account { Id = "A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u", Balance = 4389.21m, Created = new DateTime(2026, 4, 16, 0, 0, 0, DateTimeKind.Utc), }; string json = JsonConvert.SerializeObject(account, Formatting.Indented); Console.WriteLine(json); } } }儲存檔案,然後用指令
dotnet run建立並執行應用程式。 輸出是程式代碼中Account物件的 JSON 表示:{ "Id": "A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u", "Balance": 4389.21, "Created": "2026-04-16T00:00:00Z" }
相關影片
關於使用 NuGet 進行套件管理的影片,請參考 .NET Package Management with NuGet for Beginners 以及 NuGet for Beginners。
相關內容
想了解更多如何透過 dotnet CLI 安裝及使用 NuGet 套件,請參閱以下文章: