Saltar al pie de página
.NET AYUDA

Newtonsoft Jsonpath (Cómo funciona para desarrolladores)

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.

Preguntas Frecuentes

¿Cómo instalo Newtonsoft.Json para trabajar con JSON en .NET?

Puedes instalar la biblioteca Newtonsoft.Json en tu proyecto .NET utilizando el Administrador de Paquetes NuGet. Ejecuta el comando Install-Package Newtonsoft.Json en la Consola del Administrador de Paquetes. Una vez instalado, inclúyelo en tu proyecto con using Newtonsoft.Json;.

¿Para qué se utiliza JsonConvert.DeserializeObject()?

El método JsonConvert.DeserializeObject() se utiliza para analizar datos JSON en objetos .NET. Convierte cadenas JSON en objetos del tipo T, permitiéndote trabajar con datos JSON en tus aplicaciones C#.

¿Cómo puedo manipular datos JSON usando LINQ?

LINQ to JSON es una característica proporcionada por Newtonsoft.Json, que te permite consultar y manipular objetos JSON usando la sintaxis de LINQ. Esto es útil para filtrar o buscar datos JSON de manera eficiente dentro de tus aplicaciones .NET.

¿Cómo genero un informe PDF a partir de datos JSON?

Para generar un informe PDF a partir de datos JSON, primero convierte el JSON en objetos .NET usando Newtonsoft.Json. Luego, crea una plantilla HTML usando estos datos. Usa el ChromePdfRenderer de IronPDF para convertir la plantilla HTML en un documento PDF.

¿Puedo llenar formularios PDF usando datos JSON?

Sí, puedes llenar formularios PDF con datos JSON analizando el JSON en un diccionario usando Newtonsoft.Json, luego ingresando estos datos en los campos del formulario PDF usando IronPDF, antes de guardar el documento PDF llenado.

¿Cómo puedo convertir metadatos de PDF a JSON?

Extrae los metadatos de un PDF usando IronPDF y conviértelos en una cadena JSON usando Newtonsoft.Json. Este proceso te permite almacenar y manipular fácilmente metadatos de PDF en formato JSON.

¿Cuáles son las ventajas de usar Newtonsoft.Json e IronPDF juntos?

Usar Newtonsoft.Json con IronPDF en una aplicación .NET proporciona una forma fluida de manejar datos JSON y generar o manipular archivos PDF, facilitando tareas como generación de informes dinámicos, llenado de formularios e intercambio de datos.

¿Cómo leo y escribo archivos JSON en .NET?

Para leer un archivo JSON, utiliza File.ReadAllText para cargar la cadena JSON, luego análízala con JsonConvert.DeserializeObject. Para escribir JSON, serializa un objeto usando JsonConvert.SerializeObject y guárdalo con File.WriteAllText.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más