.NET HELP

Newtonsoft Jsonpath (How it Works for Developers)

Published October 29, 2023
Share:

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
VB   C#

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)
VB   C#

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)
VB   C#

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)
VB   C#

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]
VB   C#

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
VB   C#

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
VB   C#

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
VB   C#

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 plays well with other libraries, including Newtonsoft.Json.

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
VB   C#

Use Case 1 PDF Creation from JSON Data

In reference to 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)
VB   C#

After executing this code, we expect you'll have a dictionary called reportData that contains key-value pairs that represent 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>"
VB   C#

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")
VB   C#

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)
VB   C#

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
VB   C#

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")
VB   C#

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")
VB   C#

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
VB   C#

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)
VB   C#

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.

< PREVIOUS
Math Floor C# (How it Works for Developers)
NEXT >
C# AND (How it Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >