DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on • Edited on

Introduction to JSON Serialization in ASP.NET Core Web API

JSON (JavaScript Object Notation) is a lightweight data-interchange format commonly used for transmitting data between a server and a web application. In ASP.NET Core Web API, JSON serialization is the process of converting .NET objects into JSON format for easy consumption by client applications.

This article will guide you through the process of JSON serialization in ASP.NET Core Web API and provide examples to illustrate the concepts.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  1. Visual Studio with ASP.NET Core Web API project template installed.
  2. Basic knowledge of C# and ASP.NET Core.

JSON Serialization in ASP.NET Core Web API

ASP.NET Core provides built-in support for JSON serialization through the Newtonsoft.Json library (also known as JSON.NET). JSON.NET is a popular high-performance JSON framework for .NET.

To enable JSON serialization in your ASP.NET Core Web API project, follow these steps:

Step 1: Add the Newtonsoft.Json NuGet package

Open your ASP.NET Core Web API project in Visual Studio and navigate to the Solution Explorer. Right-click on the project and select Manage NuGet Packages.

In the NuGet Package Manager, search for "Newtonsoft.Json" and click on Install to add the package to your project.

Step 2: Configure JSON serialization options

Next, you need to configure the JSON serialization options in the Startup.cs file. Open the Startup.cs file and locate the ConfigureServices method.

Inside the ConfigureServices method, add the following code to configure JSON serialization:

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

// ...

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddControllers().AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });

    // ...
}
Enter fullscreen mode Exit fullscreen mode

The code above configures the JSON serialization to use the CamelCase property names and ignore reference loops to prevent circular references.

Step 3: Serializing objects

Now that the JSON serialization is configured, you can serialize .NET objects into JSON format. In your Web API controller, create an action method that returns an object.

For example, consider the following controller that returns a list of books:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class BooksController : ControllerBase
{
    [HttpGet]
    public IActionResult GetBooks()
    {
        var books = new List<Book>
        {
            new Book { Id = 1, Title = "Book 1", Author = "Author 1" },
            new Book { Id = 2, Title = "Book 2", Author = "Author 2" }
        };

        return Ok(books);
    }
}

public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

In the code above, the GetBooks action method returns a list of Book objects. The Ok method is used to return an HTTP 200 status code along with the serialized object.

Step 4: Test the API endpoint

Build and run your ASP.NET Core Web API project. You can use tools like Postman or a web browser to test the API endpoint.

Send a GET request to https://localhost:5001/api/books, and you should receive a JSON response containing the serialized list

Top comments (0)