Deserialize JSON with C#
Categories:
Mastering JSON Deserialization in C#
Learn how to effectively deserialize JSON data into C# objects using System.Text.Json and Newtonsoft.Json, with practical examples and best practices.
JSON (JavaScript Object Notation) has become the de facto standard for data interchange on the web. In C# applications, handling JSON data is a common task, especially when interacting with APIs or external services. This article will guide you through the process of deserializing JSON strings into strongly typed C# objects, covering both the built-in System.Text.Json
library and the popular third-party Newtonsoft.Json
(Json.NET) library.
Understanding JSON Deserialization
Deserialization is the process of converting a structured data format, like JSON, into an object in an application's memory. This allows you to work with the data using familiar C# object properties and methods, rather than parsing raw strings. Both System.Text.Json
(introduced in .NET Core 3.0) and Newtonsoft.Json
provide robust mechanisms for this conversion, handling various data types, nested objects, and collections.
JSON Deserialization Process
Deserializing with System.Text.Json
System.Text.Json
is Microsoft's high-performance, low-allocation JSON library. It's built into .NET and is the recommended default for new applications. To use it, you typically define a C# class that mirrors the structure of your JSON. Attributes like [JsonPropertyName("json_property")]
can be used to map C# property names to JSON property names if they differ.
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
[JsonPropertyName("price_usd")]
public decimal Price { get; set; }
}
public class SystemTextJsonExample
{
public static void Run()
{
string jsonString = "{\"Id\":1,\"Name\":\"Laptop\",\"price_usd\":1200.50}";
Product product = JsonSerializer.Deserialize<Product>(jsonString);
Console.WriteLine($"Product: {product.Name}, Price: {product.Price}");
}
}
Example of deserializing a simple JSON string using System.Text.Json
.
System.Text.Json
, ensure your C# property names match your JSON keys exactly, or use [JsonPropertyName("jsonKey")]
to explicitly map them. Case-insensitivity can be configured via JsonSerializerOptions
.Deserializing with Newtonsoft.Json (Json.NET)
Newtonsoft.Json, often referred to as Json.NET, is a powerful and widely used third-party JSON framework for .NET. It offers extensive features, including flexible property mapping, custom converters, and robust error handling. Although System.Text.Json
is now built-in, Json.NET remains a popular choice, especially in projects that predate .NET Core 3.0 or require its advanced capabilities.
using System;
using Newtonsoft.Json;
public class User
{
public string Username { get; set; }
[JsonProperty("email_address")]
public string Email { get; set; }
public int Age { get; set; }
}
public class NewtonsoftJsonExample
{
public static void Run()
{
string jsonString = "{\"Username\":\"devUser\",\"email_address\":\"dev@example.com\",\"Age\":30}";
User user = JsonConvert.DeserializeObject<User>(jsonString);
Console.WriteLine($"User: {user.Username}, Email: {user.Email}");
}
}
Example of deserializing a JSON string using Newtonsoft.Json
.
Newtonsoft.Json
, remember to install the NuGet package. While powerful, it can sometimes have a larger footprint compared to System.Text.Json
.1. Step 1
Define your C# model: Create a class that mirrors the structure of the JSON you expect to receive. Ensure property names and types match.
2. Step 2
Install necessary packages: If using Newtonsoft.Json
, add the Newtonsoft.Json
NuGet package to your project. System.Text.Json
is built-in.
3. Step 3
Choose your deserializer: Decide between System.Text.Json.JsonSerializer.Deserialize<T>()
or Newtonsoft.Json.JsonConvert.DeserializeObject<T>()
based on project requirements.
4. Step 4
Handle potential errors: Wrap your deserialization calls in try-catch
blocks to gracefully handle malformed JSON or unexpected data types.