How to create JSON response from a class?

What is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight and human-readable data exchange format. Nowadays, most of the data transformation over the web happens in the form of JSON.

How to create a JSON string with the C# class?

First of all, create a new Web API project in Visual Studio. You may use any version of the .NET framework. For this article, I am using .NET 6 with Visual Studio 2022.

Once you create your project in Visual Studio, add a class within your project as shown in the below code snippet.

public class Response
{
    public string? ResponseId { get; set; }
    public string? StatusCode { get; set; }            
    public string?  Message { get; set; }
}

Next, add a controller class within your project. Then add an action method within the controller file.

namespace ProjectDemo.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        [HttpGet]
        [Route("Check")]
        public IActionResult CheckResponse()
        {
            return Ok();
        }
    }
}

To create a JSON format for the CheckResponse() method, we will make the object of the Response class as shown in the below code snippet.

Response res = new Response()
            {
                ResponseId = Guid.NewGuid().ToString(),
                StatusCode = "200",
                Message =  "Service Executed Successfully"
            };

The complete Controller class file code snippet.

 [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        [HttpGet]
        [Route("Check")]
        public IActionResult CheckResponse()
        {
            //Write your code here
            Response res = new Response()
            {
                ResponseId = Guid.NewGuid().ToString(),
                StatusCode = "200",
                Message =  "Service Executed Successfully"
            };

            return Ok(res);
        }
    }

Now run your project and hit the URL – <localhost:port>/api/Product/Check

You will get the response in the below JSON format.

{
  "responseId": "d5cc5fab-38ef-4c8d-ab35-e467128b56b8",
  "statusCode": "200",
  "message": "Service Executed Successfully"
}

Hope this article is useful to you.

Leave a Comment

RSS
YouTube
YouTube
Instagram