In a previous article, we explored how C# records simplify API data handling by reducing boilerplate code and providing immutability and value-based equality. If you haven't read it yet, you can check it out:
Simplifying API Data Handling with C# Records
Sebastian Van Rooyen ・ Aug 15
Now, let's dive deeper into how you can use records to handle more complex JSON structures, particularly those with multiple levels of depth.
Handling Two-Level JSON Data with Records
JSON data isn't always flat; it often contains nested objects. Fortunately, records in C# can handle this complexity with ease. Let's consider a JSON structure that is two levels deep:
{
"User": {
"Id": 1,
"Name": "Sebastian Van Rooyen",
"ContactInfo": {
"Email": "sebastiandevelops@example.com",
"Phone": "123-456-7890"
}
}
}
In this JSON, ContactInfo
is a nested object within the User
object. We'll use nested records to represent this structure in C#.
Step 1: Defining Nested Records
We'll define a record for each level of the JSON structure. Here's how you can create nested records:
public record ContactInfo(string Email, string Phone);
public record User(int Id, string Name, ContactInfo ContactInfo);
public record Root(User User);
-
ContactInfo
represents the nestedContactInfo
object within theUser
object. -
User
includesId
,Name
, and aContactInfo
property. -
Root
is the top-level record containing theUser
record.
Step 2: Making an API Call and Deserializing the JSON
Let's fetch the JSON data using HttpClient
and deserialize it into the nested records:
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var client = new HttpClient();
// API call
var response = await client.GetAsync("https://example.com/user");
// Ensure the response is successful
response.EnsureSuccessStatusCode();
// Read the response content as a string
var jsonResponse = await response.Content.ReadAsStringAsync();
// Deserialize the JSON string into the Root record
var root = JsonSerializer.Deserialize<Root>(jsonResponse);
// Output the user details
Console.WriteLine($"ID: {root.User.Id}");
Console.WriteLine($"Name: {root.User.Name}");
Console.WriteLine($"Email: {root.User.ContactInfo.Email}");
Console.WriteLine($"Phone: {root.User.ContactInfo.Phone}");
}
}
Step 3: Understanding the Output
When you run this code, it will output:
ID: 1
Name: Sebastian Van Rooyen
Email: sebastiandevelops@example.com
Phone: 123-456-7890
Why Use Nested Records?
Using nested records allows you to:
- Maintain Readability: Keep your code clean and maintainable by clearly reflecting the structure of the JSON data.
- Ensure Immutability: Benefit from the immutability of records, ensuring that your data objects remain unchanged after initialization.
- Leverage Value Equality: Use value-based equality checks, even with complex nested structures.
Handling nested JSON data in C# doesn't have to be complicated. With records, you can easily model and deserialize complex JSON structures with minimal code, keeping your application clean and maintainable. Whether you're working with simple or nested JSON, records offer a powerful way to manage your API data.
If you're interested in learning more about using records with API data, don't forget to check out my previous article where I cover the basics.