.NET 帮助

Newtonsoft Jsonpath(开发人员如何使用)

如果您曾经在 .NET 中处理过 JSON 数据,您可能遇到过Newtonsoft.Json库,这是一个流行的高性能 JSON 框架。 本教程旨在帮助初学者和中级用户有效地理解和使用这个功能强大的库,重点是其系统参考、文档和任何相关的版本更新。

入门

要开始使用 Newtonsoft.Json,首先需要将其安装到您的 .NET 项目中。 这可以通过 .NET 软件包管理器 NuGet 来完成。 在 NuGet 软件包管理器控制台中,键入

:InstallCmd Install-Package Newtonsoft.Json
:InstallCmd Install-Package Newtonsoft.Json
SHELL

安装成功后,通过添加以下 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

修改和编写 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

LINQ 到 JSON

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
$vbLabelText   $csharpLabel

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(开发者如何使用):图 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(开发人员如何使用):图2

用例 3 将 PDF 元数据转换为 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 对象包含诸如 AuthorTitleCreateDate 等属性。这些属性被序列化为一个 JSON 字符串并写入名为“metadata.json”的文件中。

Newtonsoft Jsonpath(如何为开发者工作):图 3

结合 Newtonsoft.Json 和 IronPDF,您可以在 PDF 文件和 JSON 之间进行数据转换,从而满足各种使用情况。

结论

总之,Newtonsoft.Json 和 IronPDF 一起为在 .NET 中处理 JSON 数据和生成 PDF 文件提供了强大而灵活的解决方案。 通过使用 Newtonsoft.Json 将 JSON 数据解析为 .NET 对象或字典,我们可以处理这些数据并将其用于各种场合,例如填写 PDF 表单或根据模板生成动态 PDF 报告。 IronPDF 使创建和管理 PDF 的过程变得简单而高效。

本文介绍了这些库,重点介绍了它们的一些核心功能。 然而,这两个库还可以提供更多。 我们强烈建议您查阅这些工具的大量文档,深入了解其特点和功能。

如果您有兴趣尝试IronPDF,他们提供IronPDF的免费试用版,以便您可以探索其功能并评估它是否符合您的需求,然后再购买。 一旦您决定继续使用IronPDF,许可费用起始于IronPDF Licensing Options,其中包括我们讨论过的所有功能的持续访问、支持和更新。 这将确保您获得在 .NET 项目中有效生成、管理和处理 PDF 文件的工具和帮助。

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
Math Floor C#(开发者如何使用)
下一步 >
C# 和(它如何为开发人员工作)