跳過到頁腳內容
.NET幫助

Newtonsoft Jsonpath(開發者的工作原理)

如果您曾在 .NET 中處理 JSON 資料,您可能會接觸到 Newtonsoft.Json 函式庫,這是一個適用於 .NET 的熱門高效能 JSON 框架。 本教學旨在幫助初級和中級使用者有效地瞭解和使用這個功能強大的函式庫,並重點介紹其系統參考、文件和任何相關的發行更新。

開始

若要開始使用 Newtonsoft.Json,您首先需要將它安裝到您的 .NET 專案中。 這可以透過 .NET 套件管理員 NuGet 來完成。 在 NuGet Package Manager Console 中,輸入:

Install-Package Newtonsoft.Json

安裝成功後,請加入下列 using 語句,將此函式庫加入您的 .NET 專案:

using Newtonsoft.Json;
using Newtonsoft.Json;
Imports Newtonsoft.Json
$vbLabelText   $csharpLabel

使用 Newtonsoft.JSON 解析 JSON.

解析 JSON 基本上是將 JSON 格式的字串轉換成 .NET 應用程式中可用的資料結構的過程。 有了 Newtonsoft.Json,整個過程簡單直接。

讓我們來看看一個人的 JSON 物件範例:

{
    "Name": "Iron Developer",
    "Age": 30,
    "Email": "irondeveloper@ironsoftware.com"
}

我們可以使用 JsonConvert.DeserializeObject<T>() 方法將此 JSON 字串解析為 C# 物件,其中 T 是我們要建立的物件類型。 在本例中,我們將建立一個 Person 類別,並將 JSON 解析到該類別中。

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

string jsonString = "JSON string here";
Person person = JsonConvert.DeserializeObject<Person>(jsonString);
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

string jsonString = "JSON string here";
Person person = JsonConvert.DeserializeObject<Person>(jsonString);
Public Class Person
	Public Property Name() As String
	Public Property Age() As Integer
	Public Property Email() As String
End Class

Private jsonString As String = "JSON string here"
Private person As Person = JsonConvert.DeserializeObject(Of Person)(jsonString)
$vbLabelText   $csharpLabel

現在,person 物件將包含 JSON 字串中的值。

使用 JSON 檔案工作

您經常需要從檔案讀取或寫入 JSON 資料。讓我們看看如何使用 Newtonsoft.Json 來做到這一點。 在本例中,我們將使用 System.IO 命名空間中的 File 類。

讀取 JSON 檔案並將其解析為物件:

string path = "path to your json file";
string jsonString = File.ReadAllText(path);
Person person = JsonConvert.DeserializeObject<Person>(jsonString);
string path = "path to your json file";
string jsonString = File.ReadAllText(path);
Person person = JsonConvert.DeserializeObject<Person>(jsonString);
Dim path As String = "path to your json file"
Dim jsonString As String = File.ReadAllText(path)
Dim person As Person = JsonConvert.DeserializeObject(Of Person)(jsonString)
$vbLabelText   $csharpLabel

將物件寫入 JSON 檔案:

Person person = new Person() 
{
    Name = "John Doe",
    Age = 30,
    Email = "johndoe@example.com"
};

string path = "path to your json file";
string jsonString = JsonConvert.SerializeObject(person);
File.WriteAllText(path, jsonString);
Person person = new Person() 
{
    Name = "John Doe",
    Age = 30,
    Email = "johndoe@example.com"
};

string path = "path to your json file";
string jsonString = JsonConvert.SerializeObject(person);
File.WriteAllText(path, jsonString);
Dim person As New Person() With {
	.Name = "John Doe",
	.Age = 30,
	.Email = "johndoe@example.com"
}

Dim path As String = "path to your json file"
Dim jsonString As String = JsonConvert.SerializeObject(person)
File.WriteAllText(path, jsonString)
$vbLabelText   $csharpLabel

使用陣列工作。

在某些情況下,您的 JSON 將包含陣列。 例如,一個 Person 物件可能有一個 Friends 的陣列:

{
    "Name": "John Doe",
    "Friends": [
        {
            "Name": "Jane Doe",
            "Age": 28
        },
        {
            "Name": "Billy",
            "Age": 25
        }
    ]
}

您可以使用 foreach 循環來遍歷 JSON 陣列:

JArray friends = (JArray)jsonObject["Friends"];
foreach (JObject friend in friends)
{
    string friendName = (string)friend["Name"];
    Console.WriteLine(friendName);
}
JArray friends = (JArray)jsonObject["Friends"];
foreach (JObject friend in friends)
{
    string friendName = (string)friend["Name"];
    Console.WriteLine(friendName);
}
Dim friends As JArray = CType(jsonObject("Friends"), JArray)
For Each [friend] As JObject In friends
	Dim friendName As String = CStr([friend]("Name"))
	Console.WriteLine(friendName)
Next [friend]
$vbLabelText   $csharpLabel

注意:jsonObject 應該以從 JSON 初始化的實際 JObject 取代。

修改和編寫 JSON

Newtonsoft.Json 可輕鬆修改和編寫 JSON。 假設您需要更新 Person 物件的 Age 值。

jsonObject["Age"] = 31; // Update the age
jsonObject["Age"] = 31; // Update the age
jsonObject("Age") = 31 ' Update the age
$vbLabelText   $csharpLabel

然後再寫回字串:

string updatedJson = jsonObject.ToString();
File.WriteAllText(path, updatedJson); // Write back to the file
string updatedJson = jsonObject.ToString();
File.WriteAllText(path, updatedJson); // Write back to the file
Dim updatedJson As String = jsonObject.ToString()
File.WriteAllText(path, updatedJson) ' Write back to the file
$vbLabelText   $csharpLabel

注意:jsonObject 應該以從 JSON 初始化的實際 JObject 取代。

LINQ 至 JSON

Newtonsoft.Json 還提供使用 LINQ(語言整合查詢)查詢和操作 JSON 物件的功能。 這是非常強大的功能,因為它允許您使用所有標準的 LINQ 運算子來查詢 JSON 物件,就像使用 XML 或物件集合一樣。

以下是一個範例,顯示如何取得所有小於 30 歲的 Friends 的名稱:

var youngFriends = jsonObject["Friends"].Where(f => (int)f["Age"] < 30)
                                        .Select(f => (string)f["Name"]);
foreach (string name in youngFriends)
{
    Console.WriteLine(name);
}
var youngFriends = jsonObject["Friends"].Where(f => (int)f["Age"] < 30)
                                        .Select(f => (string)f["Name"]);
foreach (string name in youngFriends)
{
    Console.WriteLine(name);
}
Imports System

Dim youngFriends = jsonObject("Friends").Where(Function(f) CInt(Math.Truncate(f("Age"))) < 30).Select(Function(f) CStr(f("Name")))
For Each name As String In youngFriends
	Console.WriteLine(name)
Next name
$vbLabelText   $csharpLabel

注意:jsonObject 應該以從 JSON 初始化的實際 JObject 取代。

IronPDF 簡介

了解 IronPDF 是 .NET 生態系統中的一個流行庫,它允許開發人員 從 PDF 檔案中建立、編輯和擷取資料。 它的用途非常廣泛,可與其他函式庫 (包括 Newtonsoft.Json) 無縫搭配使用。

IronPDF 擅長於 HTML 至 PDF 的轉換,可確保精確保留原始版面與樣式。 它非常適合從網頁內容(如報告、發票和文件)建立 PDF。 IronPDF 支援 HTML 檔案、URL 和原始 HTML 字串,可輕鬆製作高品質的 PDF 文件。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

假設我們有一個需求,我們有 JSON 資料,而且我們想要從這些資料建立 PDF 報告。 我們可以使用 Newtonsoft.Json 來解析 JSON 資料,並使用 IronPDF 來建立 PDF。 讓我們看看如何做到這一點。

安裝 IronPdf

如同 Newtonsoft.Json,IronPDF 也可透過 NuGet 取得。 您可以使用下列指令安裝:

Install-Package IronPdf

然後,您可以將它加入您的專案中:

using IronPdf;
using IronPdf;
Imports IronPdf
$vbLabelText   $csharpLabel

用例 1:從 JSON 資料建立 PDF。

在本使用案例中,我們將示範如何使用 Newtonsoft.Json 和 IronPDF 從 JSON 資料產生 PDF 報告。 這對於根據以 JSON 格式儲存的資料來建立動態報告的應用程式可能特別有用。

以下是我們要處理的 JSON 檔案範例:

{
    "Title": "Sales Report",
    "Month": "August",
    "Year": "2023",
    "TotalSales": "10000",
    "ItemsSold": "500"
}

此 JSON 資料代表一份簡單的銷售報告。

第一步是讀取 JSON 檔案(在此命名為"data.json"),並使用 Newtonsoft.Json 將其解析為字典:

string jsonString = File.ReadAllText("data.json");
var reportData = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
string jsonString = File.ReadAllText("data.json");
var reportData = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
Dim jsonString As String = File.ReadAllText("data.json")
Dim reportData = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(jsonString)
$vbLabelText   $csharpLabel

執行此程式碼之後,您將擁有一個名為 reportData 的字典,其中包含代表 JSON 檔案中的屬性及其值的鍵值對。

接下來,我們使用 reportData 中的資料產生 HTML 模板。 reportData 字典中的鍵會被用來插入適當的值到 HTML 中:

string htmlContent = $@"
<html>
<head><title>{reportData["Title"]}</title></head>
<body>
    <h1>{reportData["Title"]}</h1>
    <p>Month: {reportData["Month"]}</p>
    <p>Year: {reportData["Year"]}</p>
    <p>Total Sales: {reportData["TotalSales"]}</p>
    <p>Items Sold: {reportData["ItemsSold"]}</p>
</body>
</html>";
string htmlContent = $@"
<html>
<head><title>{reportData["Title"]}</title></head>
<body>
    <h1>{reportData["Title"]}</h1>
    <p>Month: {reportData["Month"]}</p>
    <p>Year: {reportData["Year"]}</p>
    <p>Total Sales: {reportData["TotalSales"]}</p>
    <p>Items Sold: {reportData["ItemsSold"]}</p>
</body>
</html>";
Dim htmlContent As String = $"
<html>
<head><title>{reportData("Title")}</title></head>ignoreignore<body><h1>{reportData("Title")}</h1><p>Month: {reportData("Month")}</p><p>Year: {reportData("Year")}</p><p>Total Sales: {reportData("TotalSales")}</p><p>Items Sold: {reportData("ItemsSold")}</p></body></html>"
$vbLabelText   $csharpLabel

最後,我們使用 IronPDF 將 HTML 程式碼轉換為 PDF 文件。 我們使用 ChromePdfRenderer 建立 PDF 渲染器,使用它將 HTML 轉換為 PDF,然後儲存 PDF:

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("Report.pdf");
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("Report.pdf");
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
pdf.SaveAs("Report.pdf")
$vbLabelText   $csharpLabel

Newtonsoft Jsonpath (How It Works For Developers):圖 1

使用個案 2:JSON 至 PDF 表單

在本使用個案中,我們將讀取 JSON 資料以填入 PDF 文件中的表單欄位。 在這個範例中,讓我們考慮以下的 JSON 資料:

{
    "FirstName": "John",
    "LastName": "Smith",
    "PhoneNumber": "+19159969739",
    "Email": "John@email.com",
    "City": "Chicago"
}

此 JSON 代表一個人的個人資訊。

首先,我們使用 Newtonsoft.Json 讀取檔案中的 JSON 資料,並將其解析為字典:

string jsonString = File.ReadAllText("data.json");
var person = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
string jsonString = File.ReadAllText("data.json");
var person = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
Dim jsonString As String = File.ReadAllText("data.json")
Dim person = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(jsonString)
$vbLabelText   $csharpLabel

本軟體建立了一個名為 person 的字典,其鍵為 "FirstName"、"LastName"、"PhoneNumber"、"Email" 和 "City" 及其對應值。

接下來,我們使用 IronPdf 開啟 PDF 文件,並取得表單:

var doc = PdfDocument.FromFile("myPdfForm.pdf");
var form = doc.Form;
var doc = PdfDocument.FromFile("myPdfForm.pdf");
var form = doc.Form;
Dim doc = PdfDocument.FromFile("myPdfForm.pdf")
Dim form = doc.Form
$vbLabelText   $csharpLabel

現在我們可以使用 person 字典來填寫 PDF 文件中的表單欄位:

form.Fields[0].Value = person["FirstName"];
form.Fields[1].Value = person["LastName"];
form.Fields[2].Value = person["PhoneNumber"];
form.Fields[3].Value = person["Email"];
form.Fields[4].Value = person["City"];
form.Fields[0].Value = person["FirstName"];
form.Fields[1].Value = person["LastName"];
form.Fields[2].Value = person["PhoneNumber"];
form.Fields[3].Value = person["Email"];
form.Fields[4].Value = person["City"];
form.Fields(0).Value = person("FirstName")
form.Fields(1).Value = person("LastName")
form.Fields(2).Value = person("PhoneNumber")
form.Fields(3).Value = person("Email")
form.Fields(4).Value = person("City")
$vbLabelText   $csharpLabel

每個表單欄位都與 人名字典中的關鍵字相關聯。

最後,我們儲存填好的 PDF 表格:

doc.SaveAs("myPdfForm_filled.pdf");
doc.SaveAs("myPdfForm_filled.pdf");
doc.SaveAs("myPdfForm_filled.pdf")
$vbLabelText   $csharpLabel

此方法將建立一個新的 PDF 文件,其中的表單欄位將填入 JSON 檔案中的資料。

這展示了如何有效地使用 Newtonsoft.Json 來解析 JSON 資料,以及 IronPDF 來處理 PDF 文件。

Newtonsoft Jsonpath (How It Works For Developers):圖 2

使用個案 3:PDF Metadata 至 JSON

首先,使用 IronPDF 從 PDF 中提取元資料:

var pdf = IronPdf.PdfDocument.FromFile("document.pdf");
var metadata = pdf.MetaData;
var pdf = IronPdf.PdfDocument.FromFile("document.pdf");
var metadata = pdf.MetaData;
Dim pdf = IronPdf.PdfDocument.FromFile("document.pdf")
Dim metadata = pdf.MetaData
$vbLabelText   $csharpLabel

然後,使用 Newtonsoft.Json 將這些資料序列化為 JSON 字串:

string jsonString = JsonConvert.SerializeObject(metadata, Formatting.Indented);
File.WriteAllText("metadata.json", jsonString);
string jsonString = JsonConvert.SerializeObject(metadata, Formatting.Indented);
File.WriteAllText("metadata.json", jsonString);
Dim jsonString As String = JsonConvert.SerializeObject(metadata, Formatting.Indented)
File.WriteAllText("metadata.json", jsonString)
$vbLabelText   $csharpLabel

在這段程式碼中,metadata 物件包含 Author, Title, CreateDate 等屬性。這些內容會序列化為 JSON 字串,並寫入名為 "metadata.json" 的檔案中。

Newtonsoft Jsonpath (How It Works For Developers):圖 3

結合 Newtonsoft.Json 和 IronPDF 可讓您在 PDF 檔案和 JSON 之間轉換資料,滿足廣泛的使用情況。

結論

總而言之,Newtonsoft.Json 和 IronPDF 共同提供了一個功能強大且靈活的解決方案,可在 .NET 中處理 JSON 資料並產生 PDF 檔案。 透過 Newtonsoft.Json 將 JSON 資料解析成 .NET 物件或字典,我們就可以操作這些資料,並將其用於各種情境中,例如填入 PDF 表單或從範本中產生動態 PDF 報告。 IronPDF 讓 PDF 的建立與管理過程變得直接且有效率。

這篇文章介紹了這些函式庫,強調了它們的一些核心功能。 然而,這兩個函式庫還有更多的功能。 我們強烈建議您查閱其豐富的說明文件,深入瞭解其特色與功能。

如果您有興趣試用 IronPDF,他們會提供 免費試用 IronPDF 的機會,讓您可以探索其功能,並在購買前評估它是否符合您的需求。 一旦您決定繼續使用 IronPDF,授權將從IronPDF授權選項開始,其中包括繼續使用我們討論過的所有功能以及支援和更新。 這可確保您在 .NET 專案中有效地產生、管理及處理 PDF 檔案時,能獲得相關的工具與協助。

常見問題解答

如何安裝 Newtonsoft.Json 以在 .NET 中處理 JSON?

您可以使用 NuGet Package Manager 在您的 .NET 專案中安裝 Newtonsoft.Json 函式庫。在套件管理員控制台執行指令 Install-Package Newtonsoft.Json。安裝完成後,使用 using Newtonsoft.Json; 將它包含在您的專案中。

JsonConvert.DeserializeObject() 用來做什麼?

JsonConvert.DeserializeObject() 方法用於將 JSON 資料解析為 .NET 物件。它將 JSON 字串轉換成 T 類型的物件,讓您可以在 C# 應用程式中使用 JSON 資料。

如何使用 LINQ 操作 JSON 資料?

LINQ to JSON 是 Newtonsoft.Json 提供的一項功能,可讓您使用 LINQ 語法查詢和操作 JSON 物件。這對於在您的 .NET 應用程式中有效率地過濾或搜尋 JSON 資料非常有用。

如何從 JSON 資料產生 PDF 報告?

若要從 JSON 資料產生 PDF 報告,請先使用 Newtonsoft.Json 將 JSON 轉換為 .NET 物件。然後,使用這些資料建立 HTML 模板。使用 IronPDF 的 ChromePdfRenderer 將 HTML 模板轉換成 PDF 文件。

我可以使用 JSON 資料填寫 PDF 表單嗎?

是的,您可以使用 Newtonsoft.Json 將 JSON 解析成字典,然後使用 IronPDF 將這些資料填入 PDF 表單欄位,最後再儲存填入的 PDF 文件,如此即可使用 JSON 資料填入 PDF 表單。

如何將 PDF 元資料轉換為 JSON?

使用 IronPDF 從 PDF 擷取元資料,並使用 Newtonsoft.Json 將其轉換為 JSON 字串。此過程能讓您輕鬆地以 JSON 格式儲存及處理 PDF 元資料。

同時使用 Newtonsoft.Json 和 IronPDF 有哪些優點?

在 .NET 應用程式中使用 Newtonsoft.Json 與 IronPDF for .NET 可提供處理 JSON 資料以及產生或處理 PDF 檔案的無縫方式,有助於動態報表產生、表單填寫和資料交換等工作。

如何在 .NET 中讀寫 JSON 檔案?

若要讀取 JSON 檔案,請使用 File.ReadAllText 載入 JSON 字串,然後再使用 JsonConvert.DeserializeObject 解析它。要寫 JSON,使用 JsonConvert.SerializeObject 序列化物件,然後用 File.WriteAllText 儲存。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。