在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
如果您曾在 .NET 中處理過 JSON 數據,您可能會遇到過 Newtonsoft.Json 库,一個受歡迎的高效能 JSON 框架,用於 .NET。此教學目的是幫助初學者和中級用戶有效地理解和使用這個強大的庫,重點在於它的系統引用、文件以及任何相關的版本更新。
要開始使用 Newtonsoft.Json,您首先需要將其安裝到您的 .NET 專案中。這可以通過 NuGet,也就是 .NET 的套件管理工具來完成。在 NuGet 套件管理主控台中,輸入:
Install-Package Newtonsoft.Json
安裝成功後,通過添加以下 using 語句將庫添加到您的 .NET 項目中:
using Newtonsoft.Json;
using Newtonsoft.Json;
Imports Newtonsoft.Json
Newtonsoft.JSON
解析 JSON解析 JSON 本质上是将 JSON 格式的字符串转换为在 .NET 应用程序中可用的数据结构的过程。使用 Newtonsoft.Json,这个过程非常简单。
让我们来看一个人的示例 JSON 对象:
{
"Name": "Iron Developer",
"Age": 30,
"Email": "irondeveloper@ironsoftware.com"
}
我們可以使用 JsonConvert.DeserializeObject
將這個 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)
現在,person
物件將包含來自 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)
將物件寫入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)
在某些情況下,您的 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]
Newtonsoft.Json 讓修改和撰寫JSON變得輕而易舉。假設你需要更新我們的 Person
對象的 Age
值。
jsonObject ["Age"] = 31; // update the age
jsonObject ["Age"] = 31; // update the age
jsonObject ("Age") = 31 ' update the age
然後將其寫回字串:
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
Newtonsoft.Json 還提供使用 LINQ 查詢和操作 JSON 對象的功能。 (語言集成查詢). 這非常強大,因為它允許您使用所有標準的 LINQ 運算符查詢 JSON 物件,就像您對 XML 或物件集合所做的一樣。
以下是如何獲取所有朋友姓名且年齡小於 30 的範例:
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
IronPDF 是.NET生態系統中受歡迎的庫,它允許開發人員 建立,編輯和提取 PDF 文件中的數據。它非常多才多藝,並且與其他庫,如 Newtonsoft.Json 相互配合良好。
假設我們有一個需求,我們有 JSON 數據,並且我們想從這些數據創建一個 PDF 報告。我們可以使用 Newtonsoft.Json 來解析 JSON 數據,並使用 IronPDF 來創建 PDF。讓我們看看如何做到這一點。
與 Newtonsoft.Json 一樣,IronPDF 也可通過 NuGet 獲取。您可以使用以下命令進行安裝:
Install-Package IronPdf
然後,您可以通過添加將其包含在您的專案中:
using IronPdf;
using IronPdf;
Imports IronPdf
關於此使用案例,我們將展示如何使用 Newtonsoft.Json 和 IronPDF 從 JSON 數據生成 PDF 報告。這對於基於 JSON 格式數據創建動態報告的應用程序特別有用。
這是一個我們將使用的示例 JSON 文件:
{
"Title": "Sales Report",
"Month": "August",
"Year": "2023",
"TotalSales": "10000",
"ItemsSold": "500"
}
這些 JSON 數據代表一個簡單的銷售報告。
第一步是使用 Newtonsoft.Json 讀取名為 'data.json' 的 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)
執行此代碼後,我們預期你將擁有一個名為 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>"
最後,我們使用 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")
在這個用例中,我們將讀取 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)
此軟體建立一個名為 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
我們現在可以使用 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")
每個表單欄位都與person字典中的鍵相關聯。
最後,我們將填寫完畢的 PDF 表單保存下來:
doc.SaveAs("myPdfForm_filled.pdf");
doc.SaveAs("myPdfForm_filled.pdf");
doc.SaveAs("myPdfForm_filled.pdf")
此方法將使用 JSON 檔案中的數據來填寫表單字段,從而創建一個新的 PDF 文件。
這展示了如何有效地使用 Newtonsoft.Json
解析 JSON 數據以及使用 IronPDF 操作 PDF 文件。
首先,使用 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
接著,使用 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)
在這段代碼中,metadata
物件包含如 Author
、Title
、CreateDate
等屬性。這些屬性會被序列化為 JSON 字串並寫入名為 "metadata.json" 的檔案中。
將Newtonsoft.Json與IronPDF結合,能夠在PDF文件和JSON之間轉換數據,滿足廣泛的使用場景。
總而言之,Newtonsoft.Json 和 IronPDF 一起為處理 JSON 數據和生成 .NET 的 PDF 文件提供了一個強大且靈活的解決方案。通過使用 Newtonsoft.Json 將 JSON 數據解析為 .NET 對象或字典,我們可以操作這些數據並在各種上下文中使用,例如填寫 PDF 表單或從模板生成動態 PDF 報告。IronPDF 使創建和管理 PDF 的過程變得簡單高效。
本文介紹了這些庫,並強調了它們的一些核心功能。然而,這些庫都有更多的功能可供探索。我們強烈建議查看他們的詳細文檔以深入了解其功能和能力。
如果您對試用 IronPDF 感興趣,他們提供了一个 免費試用,這樣你就可以探索其功能並在購買前評估其是否符合你的需求。一旦你決定繼續使用 IronPDF,授權費用從 $749 開始,這包括繼續訪問我們討論過的所有功能以及支持和更新。這確保你擁有在 .NET 專案中有效生成、管理和操作 PDF 文件所需的工具和協助。