如何在 .NET 中使用 XML 和 JSON?
使用 JSON
JSON 是一種資料格式,已成為 XML 的一種流行替代方案。它簡單明瞭,語法類似於 JavaScript 物件。事實上,JSON 代表 JavaScript 物件表示法。最新版本的 .NET 提供了對 JSON 資料的內建支援。
System.Text.Json 名稱空間提供了高效能、低分配的功能來處理 JSON 資料。這些功能包括將物件序列化為 JSON 和將 JSON 反序列化回物件。它還提供型別來建立記憶體中的文件物件模型 (DOM),用於訪問 JSON 文件中的任何元素,從而提供資料的結構化檢視。
序列化 JSON
假設您有一個名為 Point 的類,它有兩個屬性 X 和 Y,如下所示。
class Point{ public int X { get; set; } public int Y { get; set; } }
要序列化 Point 類的一個例項,您將使用 JsonSerializer 類中定義的 Serialize() 方法,該方法位於 System.Text.Json 名稱空間中。
var point = new Point { X = 10, Y = 20 }; string jsonString = JsonSerializer.Serialize(point); Console.WriteLine(jsonString); // {"X":10,"Y":20}
要以正確的格式和縮排列印 json 資料,您可以將 JsonSerializerOptions 傳遞給 Serializer 方法,並將 WriteIndented 屬性指定為 true。
string formattedString = JsonSerializer.Serialize(point, new JsonSerializerOptions { WriteIndented = true }); Console.WriteLine(formattedString);
從 JSON 反序列化
要從 JSON 資料反序列化到 C# 物件,您可以使用 JSONSerializer 類上的泛型 Deserialize<T> 方法。例如,
string jsonData = "{\"X\":10,\"Y\":20}"; Point q = JsonSerializer.Deserialize<Point>(jsonData); Console.WriteLine(q.X + " " + q.Y); // prints 10 20
使用 XML
XML 是一種非常流行的資料格式,用於儲存和傳輸資料。.NET 提供了許多 API 用於在 C# 程式語言中使用 XML。Linq to XML 是通用 XML 處理的主要機制。它提供了一個輕量級、Linq 友好的 XML 文件物件模型以及一組查詢運算子。System.XML.Linq 名稱空間包含與 Linq to XML 相關的型別。
考慮以下 XML 資料。它有一個根元素 employee,具有兩個屬性 id 和 status,其值分別為 '231' 和 'active'。該元素有三個子元素:firstname、lastname 和 salary。
<?xml version="1.0" encoding="utf-8"?> <employee id="231" status="active"> <firstname>David</firstname> <lastname>Block</lastname> <salary>45000</salary> </employee>
Linq to XML API 解析 XML 資料,並將每個元素、屬性、值和內容表示為具有儲存相關資料的屬性的物件。它形成了一個完全表示文件的物件樹,這棵樹稱為 DOM,代表文件物件模型。
XElement 和 XDocument 提供靜態 Load 和 Parse 方法,用於從 XML 資料來源構建文件物件模型。Load 從檔案、流、URL、TextReader 和 XmlReader 構建 DOM;而 Parse 從字串構建 DOM。
string path = Path.Combine("Data", "data.xml"); string xmlData = File.ReadAllText(path); XElement employee = XElement.Parse(xmlData);
Elements() 方法提供元素的所有子元素。例如 -
foreach (var elem in employee.Elements()){ Console.WriteLine(elem.Name); }
元素上的 ToString() 方法返回帶有換行符和正確格式的 XML 字串。例如 -
Console.Write(employee.ToString()); /* Prints <employee id="123" status="active"> <firstname>David</firstname> <lastname>Block</lastname> <salary>45000</salary> </employee>% */
示例
注意:JSON 庫僅包含在 .NET Core 中。對於早期版本,必須匯入 Nuget 包。
using System; using System.Text.Json; class Program{ static void Main(string[] args){ var point = new Point { X = 10, Y = 20 }; string jsonString = JsonSerializer.Serialize(point); Console.WriteLine(jsonString); // {"X":10,"Y":20} string formattedString = JsonSerializer.Serialize(point, new JsonSerializerOptions { WriteIndented = true }); Console.WriteLine(formattedString); string jsonData = "{\"X\":10,\"Y\":20}"; Point q = JsonSerializer.Deserialize<Point>(jsonData); Console.WriteLine(q.X + " " + q.Y); // prints 10 20 } } class Point{ public int X { get; set; } public int Y { get; set; } }
輸出
{"X":10,"Y":20}{ "X": 10, "Y": 20 } 10 20