Zum Fußzeileninhalt springen
.NET HILFE

Newtonsoft Jsonpath (Wie es für Entwickler funktioniert)

If you've ever worked with JSON data in .NET, you've probably come across the Newtonsoft.Json library, a popular high-performance JSON framework for .NET. This tutorial aims to help beginners and intermediate users effectively understand and use this powerful library, with a focus on its system references, documentation, and any relevant release updates.

Getting Started

To start using Newtonsoft.Json, you first need to install it into your .NET project. This can be done through NuGet, the .NET package manager. In the NuGet Package Manager Console, type:

Install-Package Newtonsoft.Json

After successful installation, add the library to your .NET project by adding the following using statement:

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

Parsing JSON with Newtonsoft.JSON

Parsing JSON is essentially the process of converting a string in JSON format into a usable data structure in your .NET application. With Newtonsoft.Json, the process is straightforward.

Let's look at a sample JSON object for a person:

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

We can parse this JSON string into a C# object using the JsonConvert.DeserializeObject<T>() method where T is the type of the object we want to create. In this case, we'll create a Person class and parse the JSON into that.

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

Now, the person object will contain the values from the JSON string.

Working with JSON Files

You'll often need to read or write JSON data from or to a file. Let's see how we can do that with Newtonsoft.Json. We'll use the File class from the System.IO namespace in this case.

To read a JSON file and parse it into an object:

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

To write an object to a JSON file:

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

Working with Arrays

In some cases, your JSON will include arrays. For instance, a Person object might have an array of Friends:

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

You can use the foreach loop to iterate over the JSON array:

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

Note: jsonObject should be replaced with an actual JObject initialized from the JSON.

Modifying and Writing JSON

Newtonsoft.Json makes it easy to modify and write JSON. Let's say you need to update the Age value of our Person object.

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

And then write it back to a string:

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

Note: jsonObject should be replaced with an actual JObject initialized from the JSON.

LINQ to JSON

Newtonsoft.Json also provides functionality for querying and manipulating JSON objects using LINQ (Language Integrated Query). This is very powerful as it allows you to use all the standard LINQ operators to query a JSON object just as you would with XML or a collection of objects.

Here's a sample showing how you can fetch the names of all Friends younger than 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

Note: jsonObject should be replaced with an actual JObject initialized from the JSON.

Introduction to IronPDF

Learn about IronPDF is a popular library in the .NET ecosystem that allows developers to create, edit, and extract data from PDF files. It's incredibly versatile and works seamlessly with other libraries, including Newtonsoft.Json.

IronPDF excels in HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for creating PDFs from web-based content such as reports, invoices, and documentation. With support for HTML files, URLs, and raw HTML strings, IronPDF easily produces high-quality PDF documents.

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

Let's assume we have a requirement where we have JSON data, and we want to create a PDF report from that data. We can use Newtonsoft.Json for parsing the JSON data and IronPDF for creating the PDF. Let's see how we can do this.

Installation of IronPDF

Like Newtonsoft.Json, IronPDF is also available through NuGet. You can install it using the following command:

Install-Package IronPdf

Then you can include it in your project by adding:

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

Use Case 1: PDF Creation from JSON Data

In this use case, we'll demonstrate how to use Newtonsoft.Json and IronPDF to generate a PDF report from JSON data. This could be particularly useful for applications that create dynamic reports based on data stored in a JSON format.

Here's a sample JSON file that we'll be working with:

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

This JSON data represents a simple sales report.

The first step is to read the JSON file, named 'data.json' here, and parse it into a dictionary using 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

After executing this code, you'll have a dictionary called reportData containing key-value pairs representing the properties and their values in the JSON file.

Next, we generate an HTML template using the data from reportData. The keys from the reportData dictionary are used to insert the appropriate values into the 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

Lastly, we use IronPDF to convert the HTML code into a PDF document. We use ChromePdfRenderer to create a PDF renderer, use it to convert the HTML to a PDF, and then save the 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): Figure 1

Use Case 2: JSON to PDF Form

In this use case, we will read JSON data to fill in form fields in a PDF document. For this example, let's consider we have the following JSON data:

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

This JSON represents personal information for a person.

First, we use Newtonsoft.Json to read the JSON data from the file and parse it into a dictionary:

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

This software creates a dictionary called the person with keys "FirstName," "LastName," "PhoneNumber," "Email," and "City" and their corresponding values.

Next, we open the PDF document using IronPdf and get the form:

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

We can now use the person dictionary to fill the form fields in the PDF document:

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

Each form field is associated with a key from the person's dictionary.

Finally, we save the filled PDF form:

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

This method will create a new PDF document with the form fields filled in with the data from the JSON file.

This demonstrates how you can effectively use Newtonsoft.Json to parse JSON data and IronPDF to manipulate PDF documents.

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

Use Case 3: PDF Metadata to JSON

First, use IronPDF to extract the metadata from the 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

Then, serialize this data into a JSON string using Newtonsoft.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

In this code, the metadata object contains properties like Author, Title, CreateDate, etc. These are serialized into a JSON string and written to a file named "metadata.json."

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

Combining Newtonsoft.Json and IronPDF allows you to convert data between PDF files and JSON, fulfilling a wide range of use cases.

Conclusion

To conclude, Newtonsoft.Json and IronPDF together provide a powerful and flexible solution for handling JSON data and generating PDF files in .NET. By parsing JSON data into .NET objects or dictionaries with Newtonsoft.Json, we can manipulate that data and use it in various contexts, such as filling in PDF forms or generating dynamic PDF reports from templates. IronPDF makes the process of creating and managing PDFs straightforward and efficient.

This article introduced the libraries, highlighting some of their core functionality. However, both libraries have much more to offer. We strongly recommend checking their extensive documentation for a deep dive into their features and capabilities.

If you're interested in trying out IronPDF, they offer a free trial of IronPDF so you can explore its features and evaluate whether it meets your needs before purchasing. Once you decide to continue with IronPDF, licensing starts at IronPDF Licensing Options which includes continued access to all the features we discussed and support and updates. This ensures you have the tools and assistance to effectively generate, manage, and manipulate PDF files in your .NET projects.

Häufig gestellte Fragen

Wie installiere ich Newtonsoft.Json zum Arbeiten mit JSON in .NET?

Sie können die Newtonsoft.Json-Bibliothek in Ihrem .NET-Projekt mit dem NuGet-Paketmanager installieren. Führen Sie den Befehl Install-Package Newtonsoft.Json in der Paket-Manager-Konsole aus. Sobald installiert, binden Sie es in Ihr Projekt ein mit using Newtonsoft.Json;.

Wofür wird JsonConvert.DeserializeObject() verwendet?

Die Methode JsonConvert.DeserializeObject() wird verwendet, um JSON-Daten in .NET-Objekte zu parsen. Sie konvertiert JSON-Strings in Objekte vom Typ T, sodass Sie mit JSON-Daten in Ihren C#-Anwendungen arbeiten können.

Wie kann ich JSON-Daten mit LINQ manipulieren?

LINQ to JSON ist eine Funktion, die von Newtonsoft.Json bereitgestellt wird, mit der Sie JSON-Objekte mit LINQ-Syntax abfragen und manipulieren können. Dies ist nützlich, um JSON-Daten innerhalb Ihrer .NET-Anwendungen effizient zu filtern oder zu durchsuchen.

Wie generiere ich einen PDF-Bericht aus JSON-Daten?

Um einen PDF-Bericht aus JSON-Daten zu erstellen, konvertieren Sie zuerst das JSON in .NET-Objekte mit Newtonsoft.Json. Erstellen Sie dann eine HTML-Vorlage unter Verwendung dieser Daten. Verwenden Sie ChromePdfRenderer von IronPDF, um die HTML-Vorlage in ein PDF-Dokument zu konvertieren.

Kann ich PDF-Formulare mit JSON-Daten ausfüllen?

Ja, Sie können PDF-Formulare mit JSON-Daten ausfüllen, indem Sie das JSON mit Newtonsoft.Json in ein Wörterbuch parsen und dann die Felder des PDF-Formulars mit diesen Daten befüllen, bevor Sie das ausgefüllte PDF-Dokument speichern.

Wie kann ich PDF-Metadaten in JSON konvertieren?

Extrahieren Sie die Metadaten aus einem PDF mit IronPDF und konvertieren Sie sie in einen JSON-String mit Newtonsoft.Json. Dieser Prozess ermöglicht es Ihnen, PDF-Metadaten einfach im JSON-Format zu speichern und zu manipulieren.

Was sind die Vorteile der Verwendung von Newtonsoft.Json und IronPDF zusammen?

Die Verwendung von Newtonsoft.Json mit IronPDF in einer .NET-Anwendung bietet eine nahtlose Möglichkeit, JSON-Daten zu handhaben und PDF-Dateien zu erstellen oder zu manipulieren, was Aufgaben wie die dynamische Berichtserstellung, das Ausfüllen von Formularen und den Datenaustausch erleichtert.

Wie lese und schreibe ich JSON-Dateien in .NET?

Um eine JSON-Datei zu lesen, verwenden Sie File.ReadAllText, um den JSON-String zu laden, und parsen Sie ihn dann mit JsonConvert.DeserializeObject. Zum Schreiben von JSON serialisieren Sie ein Objekt mit JsonConvert.SerializeObject und speichern es mit File.WriteAllText.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen