在使用 Newtonsoft.Json (Json.NET) 進行 JSON 反序列化時,若專案缺少必要的組件引用,會出現「找不到型別或命名空間」編譯錯誤。本文列出必須手動添加的命名空間與組件,幫助快速修復。
Install-Package Newtonsoft.Json)或從官網獲取。using Newtonsoft.Json; // 核心序列化/反序列化 API
using Newtonsoft.Json.Linq; // JObject, JArray, JToken 等 LINQ to JSON 類別
using System.Runtime.Serialization; // DataContract / DataMember 屬性(若用資料契約模式)
using System.ServiceModel; // WCF 相關,部分舊專案需求
using System.ServiceModel.Web; // WebGet/WebInvoke 等屬性
| 錯誤訊息 | 原因 | 修復 |
|---|---|---|
| The type or namespace name 'JsonConvert' could not be found | 缺少 using Newtonsoft.Json; | 添加該命名空間 |
| The type or namespace name 'JObject' could not be found | 缺少 using Newtonsoft.Json.Linq; | 添加該命名空間 |
| Reference required to assembly 'System.Runtime.Serialization' | 專案未引用 System.Runtime.Serialization.dll | 右鍵專案 → Add Reference → Assemblies → Framework → 勾選 System.Runtime.Serialization |
| Reference required to assembly 'System.ServiceModel.Web' | 專案未引用 System.ServiceModel.Web.dll | 同理添加引用 |
string json = "{\"Name\":\"Tom\",\"Age\":25}";
var obj = JsonConvert.DeserializeObject(json);
Console.WriteLine(obj.Name); // 輸出 Tom
// 或強型別
public class Person { public string Name { get; set; } public int Age { get; set; } }
Person p = JsonConvert.DeserializeObject(json);
現代專案建議直接使用內建的 System.Text.Json(命名空間 System.Text.Json),無需額外套件,效能更優。僅在需 Json.NET 獨有功能(如 TypeNameHandling、自定義 Converter 複雜場景)時才引入 Newtonsoft.Json。
記住以上組件與命名空間,即可消除 Json.NET 反序列化的引用錯誤,專注於業務邏輯開發。