.NET HELP

Newtonsoft Jsonpath (How it Works for Developers)

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.

Frequently Asked Questions

What is Newtonsoft.Json and why is it popular among .NET developers?

Newtonsoft.Json is a high-performance JSON framework for .NET that is widely used for parsing and manipulating JSON data. It is popular because of its ease of use, flexibility, and comprehensive features for handling JSON data in .NET applications.

How do I install Newtonsoft.Json in a .NET project?

You can install Newtonsoft.Json in a .NET project using the NuGet Package Manager. In the NuGet Package Manager Console, type the command: Install-Package Newtonsoft.Json. After installation, include it in your project by adding the using statement: using Newtonsoft.Json;

How can I parse JSON data into a C# object using Newtonsoft.Json?

To parse JSON data into a C# object, use the JsonConvert.DeserializeObject() method where T is the type of the object you want to create. For example, you can parse a JSON string into a Person class object with the following code: Person person = JsonConvert.DeserializeObject(jsonString);

How can I read and write JSON files using Newtonsoft.Json?

To read a JSON file, use the File.ReadAllText method to get the JSON string and then parse it using JsonConvert.DeserializeObject. To write an object to a JSON file, serialize the object using JsonConvert.SerializeObject and save it using File.WriteAllText.

How do I work with JSON arrays using Newtonsoft.Json?

You can work with JSON arrays by using JArray to parse the array and iterate over it using a foreach loop. For example, JArray friends = (JArray)jsonObject['Friends']; foreach (JObject friend in friends) { string friendName = (string)friend['Name']; Console.WriteLine(friendName); }

What is LINQ to JSON and how is it used with Newtonsoft.Json?

LINQ to JSON is a feature of Newtonsoft.Json that allows querying and manipulating JSON objects using LINQ syntax. It is powerful for searching and filtering JSON data. For example, you can fetch names of friends younger than 30 using LINQ queries on JSON arrays.

How can I create a PDF from JSON data using IronPDF?

To create a PDF from JSON data using IronPDF, first parse the JSON data into a .NET object or dictionary using Newtonsoft.Json. Then, generate an HTML template using this data and convert it into a PDF using IronPDF's ChromePdfRenderer.

How can I fill PDF form fields with JSON data using IronPDF?

First, parse the JSON data into a dictionary using Newtonsoft.Json. Then, open the PDF document with IronPDF and use the form fields to populate them with values from the dictionary, finally saving the filled PDF form.

Can I extract PDF metadata and convert it to JSON using IronPDF and Newtonsoft.Json?

Yes, you can extract PDF metadata using IronPDF and then serialize this metadata into a JSON string using Newtonsoft.Json. This allows for easy storage and manipulation of PDF metadata in JSON format.

What are the benefits of combining Newtonsoft.Json and IronPDF in a .NET application?

Combining Newtonsoft.Json and IronPDF allows developers to efficiently handle JSON data and generate, manipulate, and manage PDF files within .NET applications. This combination supports various use cases, including dynamic report generation and form filling.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.
< PREVIOUS
Math Floor C# (How it Works for Developers)
NEXT >
C# AND (How it Works For Developers)