DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on • Edited on

14

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

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging →

👋 Kindness is contagious

Explore this insightful post in the vibrant DEV Community. Developers from all walks of life are invited to contribute and elevate our shared know-how.

A simple "thank you" could lift spirits—leave your kudos in the comments!

On DEV, passing on wisdom paves our way and unites us. Enjoyed this piece? A brief note of thanks to the writer goes a long way.

Okay