DEV Community

Cover image for Working with Nested JSON Data Using C# Records
Sebastian Van Rooyen
Sebastian Van Rooyen

Posted on

Working with Nested JSON Data Using C# Records

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:

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"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
  • ContactInfo represents the nested ContactInfo object within the User object.
  • User includes Id, Name, and a ContactInfo property.
  • Root is the top-level record containing the User 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}");
    }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)