Parsing JSON Data in C#: Using Newtonsoft.Json and System.Text.Json
Learn efficient methods for parsing JSON data in C#. This tutorial compares using Newtonsoft.Json and `System.Text.Json`, demonstrating how to parse JSON strings into C# objects, handle different data structures, and choose the best approach based on your project needs and dependencies.
Parsing JSON Data in C#
Introduction
Parsing JSON (JavaScript Object Notation) data is a common task in C# development, especially when working with web APIs or other data sources that use JSON. This article explains how to parse JSON using different methods in C#.
Method 1: Using Newtonsoft.Json
Newtonsoft.Json (often shortened to Json.NET) is a popular third-party library. To use it, you first need to install the NuGet package:
Installing Newtonsoft.Json
Install-Package Newtonsoft.Json
Here's how to parse a JSON string using Json.NET:
Parsing JSON with Newtonsoft.Json
using Newtonsoft.Json;
string jsonString = @"{
'name': 'John',
'age': 30,
'city': 'New York'
}";
dynamic data = JsonConvert.DeserializeObject(jsonString);
Console.WriteLine($"Name: {data.name}");
Console.WriteLine($"Age: {data.age}");
Console.WriteLine($"City: {data.city}");
Json.NET's `DeserializeObject` method parses the JSON string into a dynamic object, allowing easy access to its properties.
Method 2: Using System.Text.Json
Starting with .NET Core 3.0 and .NET 5+, C# includes the built-in `System.Text.Json` namespace. It's a performant and lightweight option.
Parsing JSON with System.Text.Json
using System.Text.Json;
string jsonString = @"{
'name': 'John',
'age': 30,
'city': 'New York'
}";
using (JsonDocument doc = JsonDocument.Parse(jsonString)) {
JsonElement root = doc.RootElement;
Console.WriteLine($"Name: {root.GetProperty("name").GetString()}");
Console.WriteLine($"Age: {root.GetProperty("age").GetInt32()}");
Console.WriteLine($"City: {root.GetProperty("city").GetString()}");
}
This uses `JsonDocument.Parse` to parse the JSON, then accesses properties using `GetProperty`.
Method 3: Using JavaScriptSerializer (Less Recommended)
The `JavaScriptSerializer` class (in `System.Web.Script.Serialization`) is an older method. While functional for simpler JSON, it lacks features and performance of the above methods and is generally not recommended for new projects.
(Example using JavaScriptSerializer would be added here, along with a note about its limitations compared to Newtonsoft.Json and System.Text.Json.)
Conclusion
Both Newtonsoft.Json and System.Text.Json are powerful options for parsing JSON in C#. `System.Text.Json` is the built-in, recommended approach for new .NET projects, while Newtonsoft.Json remains a widely used and feature-rich third-party library.